使用PHP和cURL将数据发布到服务器

时间:2016-10-22 22:40:17

标签: php json curl

我有以下数据通过我的API发布到服务器。

Request Body: 
{
  "nutrients": {
    "protein": "beans",
    "fats": "oil",
    "carbohdrate": "starch"

  }
}

每次运行脚本时,都会出现以下错误

{"errors":[{"status":"400","code":"031","title":"payload not parseable","detail":"Invalid formatting of the request payload."},{"status":"400","code":"026","title":"payload missing","detail":"No payload describing the resource object included in the request."}]}

这似乎是因为我没有添加变量"营养素"在要发布的数据数组中。

有人能帮助我吗?以下是我到目前为止的努力。感谢

<?php
$url = "https://myapi_site.com/server/";  
$data = array(
        'protein' => 'beans',
        'fats' => 'oil',
        'carbohdrate'  => 'starch'          
); 
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
?>

1 个答案:

答案 0 :(得分:0)

您发布的PHP数组尚未转换为JSON ...您想发布JSON本身。以下是发布JSON字符串的方法。

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

您可以使用json_encode将PHP数组编码为JSON:

http://php.net/json_encode

定义您的$data变量,如下所示:

$data = array(
  'nutrients' => array(
        'protein' => 'beans',
        'fats' => 'oil',
        'carbohdrate'  => 'starch',
   ),
); 

您可以回显$data变量以查看它包含正确的JSON数据:

echo $data;