dua27031
dua27031
2018-03-26 21:46
浏览 53

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

I'm POSTing to an API that expects a json array called "updateRecord" in the body. I've tried a hundred different methods of getting the data across, but each method fails except for me literally writing the array as escaped text inside the CURLOPT_POSTFIELDS option.

$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;

For static test data to prove the API works, this is fine, but I am lost on how to take a pre-existing array in PHP and convert it into a format that will work here, like:

curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujia3441
    doujia3441 2018-03-26 21:51
    已采纳

    you could use json_encode() to serialize your array:

    $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 will look like :

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

相关推荐