json_encode()返回null表示编码失败,常见原因包括资源类型、循环引用或非UTF-8编码;应配合json_last_error_msg()排查,并预处理数据。
PHP 中 json_encode() 返回 null 不代表“没结果”,而是明确表示编码失败。最常见原因是传入了无法序列化的数据类型,比如资源句柄(resource)、闭包(Closure)、或包含循环引用的数组/对象。
json_last_error() 和 json_last_error_msg() 立刻检查错误原因,不要只看返回值是否为 null
is_array() 或 is_object() 过滤,再用 array_walk_recursive() 预处理掉 resource 或 NULL 值(如替换成 '' 或 '[resource]')json_encode() 失败json_decode() 默认返回 stdClass 对象,不是关联数组。这点容易在遍历时出错——比如用 foreach ($data as $k => $v) 时,若误以为是数组却拿到对象,会触发 “Cannot use object as array” 错误。
true:写成 json_decode($json, true),强制返回关联数组->(如 $obj->name),不能用 ['name']

true 更易处理,避免类型混用引发 Notice老版本 PHP 需要手动调用 json_last_error() 判断,代码冗长。PHP 7.3 起支持 JSON_THROW_ON_ERROR 标志,让 json_encode() 和 json_decode() 在失败时直接抛出 JsonException 异常。
try {
$arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
error_log('JSON 解析失败: ' . $e->getMessage());
$arr = [];
}
|)组合,不能单独传JsonException,不是 Exception,捕获时需写全名或 use 声明用 file_get_contents() + json_decode() 一次性加载整个文件,遇到几十 MB 的 JSON 就容易 OOM。这不是 JSON 函数的问题,而是加载方式不合理。
stream_get_contents() 配合 fopen() 分块读取,但注意 JSON 必须是单层结构(如纯数组),否则无法安全切分jsond 扩展(需编译安装)或纯 PHP 的 JsonStreamingParser 库,逐行/逐事件解析,内存占用恒定json_encode(),既不报错也不警告,只默默返回 null;而开发者往往只检查空值,没查 json_last_error_msg(),最终卡在“为什么 JSON 没生成出来”。