PHP中json_decode解析API返回值时得到NULL的问题求助
解决file_get_contents获取加密货币API数据返回NULL的问题
问题原因
API返回的内容采用了gzip压缩,file_get_contents默认不会自动解压缩获取到的二进制压缩数据,导致json_decode无法解析无效的JSON内容,最终返回NULL。
解决方法
方法1:手动解压缩gzip内容
通过stream_context_create添加请求头告知服务器接受压缩内容,再用gzdecode解压缩后解析JSON:
// 创建HTTP请求上下文,声明接受gzip压缩 $context = stream_context_create([ 'http' => [ 'header' => 'Accept-Encoding: gzip, deflate' ] ]); // 获取压缩内容并解压缩,再解析JSON $compressed_content = file_get_contents($meow_base_api, false, $context); $meow_base_data = json_decode(gzdecode($compressed_content), true); var_dump($meow_base_data);
方法2:使用cURL自动处理压缩
cURL支持自动解压缩gzip内容,比file_get_contents更可靠:
$ch = curl_init($meow_base_api); // 设置返回内容不直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 启用gzip/deflate解压缩 curl_setopt($ch, CURLOPT_ENCODING, ''); // 执行请求并获取响应 $response = curl_exec($ch); curl_close($ch); // 解析JSON数据 $meow_base_data = json_decode($response, true); var_dump($meow_base_data);
排查技巧
如果不确定解析失败原因,可以在json_decode后调用json_last_error_msg()查看具体错误:
$compressed_content = file_get_contents($meow_base_api); $meow_base_data = json_decode($compressed_content, true); var_dump(json_last_error_msg()); // 会输出类似"Syntax error",确认是内容格式问题
内容的提问来源于stack exchange,提问作者jpgerb
相关产品推荐
相关产品推荐

