我需要使用curl向外部http API发出POST请求.当我使用curl命令行调用API时,它返回正确的数据.但是,当我从php脚本调用它时,我很难获得正确的数据.
当我从终端使用curl命令时,我得到了正确的数据:
curl -i -H“接受:application / json”-X POST -d“type_category_id = 4”http://example.com/api/
php中我的curl_setopts()中CURLOPT_POSTFIELDS的正确格式是什么?
我尝试了以下(并失败):
$data = "type_category_id=4";
$ch = curl_init('http://example.com/api/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
?>