我有一个api链接在终端上正常工作。我使用相同的api链接在PHP中使用CURL检索数据。我试过下面的代码:
<?php
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'urlxxxxx');
// execute the request
$output = curl_exec($ch);
// output the profile information - includes the header
echo "curl response is : <br> ".($output). PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
?>
但我得到了回应:
卷曲响应是: {“error”:“JSON语法错误:格式错误的JSON字符串,无论是数组,对象,数字,字符串还是原子,在/ usr / share / perl5 / JSON处的字符偏移0(在\”(字符串结尾)\“之前) .pm第171.行\ n“}
我是CURL的新手,指导我解决它的问题。
答案 0 :(得分:1)
添加:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
所以你发送一个空的JSON对象作为参数。这是PHP的等价物
-d "{}"
从命令行。
要将其他数组放入发布数据,请使用json_encode
。
$data = array('userId' => array(),
'user_list' => array("1", "2", "3", "4", "5", "6", "7", "8")
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data);
答案 1 :(得分:0)
您需要将方法设置为&#39; GET&#39;删除curl_setopt($ch, CURLOPT_POST, true);
或者提供有效的JSON curl_setopt($curl, CURLOPT_POSTFIELDS, "{}");