如何将字符串响应转换为JSON对象?

时间:2016-09-09 11:25:28

标签: php json curl

我正在使用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);

2 个答案:

答案 0 :(得分:2)

试试这个: -

$curl_response = curl_exec($curl);

function escapeJsonString($value) { 
    $escapers = array("\'");
    $replacements = array("\\/");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}



$curl_response = escapeJsonString($curl_response);

$curl_response = json_decode($curl_response,true);

echo '<pre>';print_r($curl_response);

echo $error = json_last_error();

参考文献: - http://www.pontikis.net/tip/?id=5

您发现有用的链接是: - https://stackoverflow.com/a/20845642/4248328

答案 1 :(得分:0)

尝试添加第二个参数&#34; assoc&#34;获取数组到json_decode函数:

$curl_response = json_decode($curl_response, true);

希望它能提供帮助。