dua27031 2018-03-26 21:46
浏览 58
已采纳

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 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"}]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试