我正在使用 curl
在一个 PHP 函数中调用第三方 API。我得到了一个 JSON 格式的响应(数据类型为字符串)。我想将该响应转换为对象或数组。我尝试过使用 json_decode()
,但是得到的是 null
。如果我在浏览器中显示响应并将该字符串响应复制粘贴到 PHP 变量中,我就可以得到值。所以我无法找出问题所在。
以下是我的代码:
$fullUrl = 'http://example.com/api/assignment/1';
$data = AesCtr::encrypt($data, 'My Key', 256);
$curl = curl_init($fullUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, ['data' => $data]);
$curl_response = curl_exec($curl);
$curl_response = json_decode($curl_response);
echo '<pre>';
print_r($curl_response);
以下是回应内容:
{"identifier":"id", "items":[{"apiResult":"INVALID", "apiResultMessage":"Invalid controls. the field 'resource' is mandatory the field 'type of item' is mandatory the field 'element id' is mandatory the field 'resource' is mandatory", "id":"", "idProject":"", "nameProject":"", "refType":"", "refId":"", "idResource":"", "nameResource":"", "idRole":"", "nameRole":"", "comment":"", "assignedWork":"", "realWork":"", "leftWork":"", "plannedWork":"", "rate":"", "realStartDate":"", "realEndDate":"", "plannedStartDate":"", "plannedEndDate":"", "dailyCost":"", "newDailyCost":"", "assignedCost":"", "realCost":"", "leftCost":"", "plannedCost":"", "idle":"", "billedWork":""}] }
我也尝试过这个。
$curl_response = str_replace("'", "\'", $curl_response);
$curl_response = json_decode($curl_response);
json_last_error_msg()
检查JSON解码错误消息。请访问http://json-parser.com/a7826645。 - Alok Patel