【发布时间】:2017-01-17 12:59:48
【问题描述】:
我正在使用 php 函数中的 curl 调用第三方 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 字符串似乎有效,json-parser.com/a7826645 尝试使用
json_last_error_msg()检查 JSON 解码错误消息 -
请不要随意在问题的部分加粗,这样会更难阅读。
-
@Anant,我已经回复了问题。
-
@AlokPatel,我知道 JSON 是有效的。但我的问题是那为什么我不能解码呢?
-
@Anant,是的,这就是响应。但请记住,它是字符串数据类型。这里看起来像对象,因为我从浏览器复制/粘贴。