php curl将有效负载发送为JSON正文

时间:2018-03-26 21:46:20

标签: php json curl post

我正在发布一个API,它需要一个名为“updateRecord”的json数组。我尝试了一百种不同的数据获取方法,但每种方法都失败了,除了我将数组作为转义文本写在CURLOPT_POSTFIELDS选项中。

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://url.com/update");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"updateRecord\":[{\"fielda\":\"77777\",
\"fieldb\":\"11.77\",\"fieldc\":\"12\",\"fieldd\":\"12\",\"fielde\":\"99\",
\"fieldf\":\"01\",\"fieldg\":\"TEST\",
\"fieldh\":\"Y\",\"fieldi\":\"Approved\"}]}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: Basic XXXXXXXXXXXXXXXXXX";
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);

echo $result;

对于静态测试数据来证明API有效,这很好,但我对如何在PHP中使用预先存在的数组并将其转换为可在此处工作的格式感到迷茫,例如:

curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);

1 个答案:

答案 0 :(得分:3)

您可以使用json_encode()来序列化您的数组:

$arr = array('updateRecord' => array(
    array(
      'fielda' => '77777',
      'fieldb' => '11.77',
      'fieldc' => '12',
      'fieldd' => '12',
      'fielde' => '99',
      'fieldf' => '01',
      'fieldg' => 'TEST',
      'fieldh' => 'Y',
      'fieldi' => 'Approved',
    ),
  ),
);

$serial = json_encode($arr) ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $serial);

$serial将如下所示:

{"updateRecord":[{"fielda":"77777","fieldb":"11.77","fieldc":"12","fieldd":"12","fielde":"99","fieldf":"01","fieldg":"TEST","fieldh":"Y","fieldi":"Approved"}]}