为何Curl返回字符串响应?如何将其转换为JSON格式?
解决PHP Curl响应字符串转JSON格式的问题
你可以使用PHP内置的json_decode()函数将返回的字符串响应转换为JSON对应的PHP数据结构(关联数组或对象):
基本用法
// 执行curl请求后,处理返回结果 $result = curl_exec($ch); // 转换为关联数组 $jsonResult = json_decode($result, true); // 或者转换为对象 // $jsonResult = json_decode($result); // 查看结果 dd($jsonResult);
完整修改后的代码示例
$dataArray = array("id"=>1234,"stringnumber"=>"123456789"); $data_string = json_encode($dataArray); $ch = curl_init('myurl'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $result = curl_exec($ch); // 转换为JSON格式对应的PHP结构 $jsonResult = json_decode($result, true); dd($jsonResult);
注意事项
- 如果
json_decode()返回null,说明返回的字符串不是有效的JSON格式,可以用json_last_error()和json_last_error_msg()排查具体错误:$jsonResult = json_decode($result, true); if (json_last_error() !== JSON_ERROR_NONE) { echo 'JSON解析错误:' . json_last_error_msg(); } - 第二个参数设为
true时,返回关联数组;不填或设为false时,返回stdClass对象,可根据业务需求选择。
内容的提问来源于stack exchange,提问作者jane mily
相关产品推荐
相关产品推荐

