【问题标题】:How to send and receive data to/from an API using CURL?如何使用 CURL 向/从 API 发送和接收数据?
【发布时间】:2014-11-02 11:24:59
【问题描述】:

我必须创建一个API。为此,我将使用 POST 以 JSON 的形式从移动设备接收数据。我必须处理这些数据并将响应也以JSON 发送回设备。 但我不知道如何获取我将收到的数据。我尝试使用CURL 进行一些测试以查看如何获取这些数据,但$_POST 始终为空。您能否告诉我如何使用CURL 将数据以JSON 格式发送到API,以及如何接收这些数据以便我可以使用它并将其作为响应发送回来?

这些是我的测试文件:

curl.php:

    //set POST variables
    $url = 'http://test.dev/test.php';
    $data = array(
        'fname' => 'Test',
        'lname' => 'TestL',
        'test' => array(
            'first' => 'TestFirst',
            'second' => 'TestSecond'
        )
    );

    //open connection
    $ch = curl_init($url);

    $json_data = json_encode($data);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($json_data))
    );

    // execute post
    $result = curl_exec($ch);

    echo $result;

    //close connection
    curl_close($ch);

测试.php:

var_dump($_POST);

我得到的回应是:

array(0) { }

【问题讨论】:

  • file_get_contents('php://') 从请求正文中获取 json 值
  • 我曾尝试使用 file_get_contents 但出现以下错误: file_get_contents(): Invalid php:// URL specified in... file_get_contents(php://): failed to open stream: operation失败...
  • file_get_contents('php://') 将获取提交到您页面的 json 数据...我认为您错过了单引号

标签: php json api curl


【解决方案1】:

您需要将 POST 数据作为 URL 查询字符串或数组传递,问题是您以 JSON 格式发布数据,但 PHP 不会自动解析 JSON,因此 $_POST 数组为空。如果需要,需要在 test.php 中自己进行解析:

$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);

同样的问题:12

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 2016-11-15
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多