You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:30:54