使用curl php时使用此api的json格式无效

时间:2016-11-16 07:01:14

标签: php json api curl

这是我的json数据

$data = array(
"api_key"=>"xxxx",  
"email_details"=> array( "fromname"=>"test",  
"subject"=>"Registration",   
"from"=>"xxx@xxx.com",   
"content"=>"test"), 
"recipients"=>["xxx@gmail.com"]
);

生成了json数据:

$str_data = json_encode($data);

它给出了json的以下格式:

{"api_key":"xxxx",
"email_details":{"fromname":"test","subject":"Registration","from":"xxx@xxx.com","content":"test"},
"recipients":["xxx@gmail.com"]}

它是有效的json格式 从此网址验证 http://jsonlint.com/

来自邮递员的

我试图运行API:

https://api.xxx.com/xxx/json?data={"api_key":"xxxx","email_details":   {"fromname":"xxx","subject":"Registration","from":"xxx@xxx.com","content":"test" },"recipients":["xxx@gmail.com"]}

给出了成功消息

当我试图从php代码运行这个api时:

$url_email="https://api.xxx.com/xxx/json?data=";

$chh = curl_init();
curl_setopt($chh, CURLOPT_URL,$url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($chh, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
   'Content-Type: application/json',                                                                                
   'Content-Length: ' . strlen($str_data))                                                                       
);  
curl_setopt($chh, CURLOPT_RETURNTRANSFER, true);
curl_exec($chh);
curl_close($chh);

我没有得到o / p 收到错误消息:

{"message":"ERROR","errorcode": "100" ,"errormessage":"Invalid JSON format used in API Call.Hence failed."}

这里有什么不对吗?

1 个答案:

答案 0 :(得分:0)

我想它应该是:

$url_email="https://api.xxx.com/xxx/json";  // no `data` here
$chh = curl_init();
curl_setopt($chh, CURLOPT_URL, $url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($chh, CURLOPT_POSTFIELDS, 'data=' . $str_data); // `data` moved here