【发布时间】:2019-01-04 11:23:22
【问题描述】:
我在做一个 post curl 请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers = ["Content-Type:application/json","Accept:application/json"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
上面的 curl 请求应该返回一个 json 格式的字符串,但是得到一个 javascript 对象形式的字符串。
string(68) "{data:{errorCode:AC01,errorMessage:SansID 53563857 is exist.}}"
当我尝试从 post man api 做同样的事情时返回完美的 json。
{"data":{"errorCode":"AC01","errorMessage":"SansID 53563857 is exist."}}
请让我知道我哪里做错了。
【问题讨论】:
-
无论你得到什么响应都不是 curl_* 函数的错。如果不了解更多信息,任何人都无法就该 API 提出建议。
-
您是否使用 var_dump() 打印响应数据?
-
我认为 API 响应没问题,请使用 json_decode() 方法将 json 转换为数组并使用 print_r 方法打印该值。
-
@sohanverma 我使用了 dd(),当 json_decode() 给出的字符串为 NULL
-
好的,请在 $result = curl_exec($ch); 之后使用 json_decode线。请使用此代码:$responseArray = json_decode($result); print_r($responseArray);死;请检查我的建议,如果仍然有同样的错误,请告诉我。