PHP JSON
核对 PHP 内置 JSON 扩展的 json_encode()、json_decode()、json_last_error() 及关键位掩码选项(JSON_UNESCAPED_UNICODE、JSON_BIGINT_AS_STRING、JSON_THROW_ON_ERROR),并在 PHP 8.4.27 实测验证。
学完这一章,你能够
- 核对 PHP 内置 JSON 扩展的 json_encode()、json_decode()、json_last_error() 及关键位掩码选项(JSON_UNESCAPED_UNICODE、JSON_BIGINT_AS_STRING、JSON_THROW_ON_ERROR),并在 PHP 8.4.27 实测验证。
PHP JSON 扩展与核心函数概览
自 PHP 5.2.0 起已内置 JSON 扩展(PHP 8.0+ 更成为不可禁用的语言核心组件),无需额外安装即可执行高效的数据序列化与反序列化。常用核心函数包括编码函数 `json_encode()`、解码函数 `json_decode()` 以及错误诊断函数 `json_last_error()`(配合 `json_last_error_msg()`)。
json_encode() 编码数组、对象与中文选项
`json_encode($value, $flags = 0, $depth = 512)` 将 UTF-8 编码的 PHP 变量转为 JSON 字符串,失败时返回 `false`(启用 `JSON_THROW_ON_ERROR` 时抛出 `JsonException`)。第二个参数为位掩码常量组合,常见标志涵盖 `JSON_HEX_QUOT`、`JSON_HEX_TAG`、`JSON_HEX_AMP`、`JSON_HEX_APOS`、`JSON_NUMERIC_CHECK`、`JSON_PRETTY_PRINT`、`JSON_UNESCAPED_SLASHES`、`JSON_FORCE_OBJECT`、`JSON_PRESERVE_ZERO_FRACTION`、`JSON_UNESCAPED_UNICODE` 与 `JSON_PARTIAL_OUTPUT_ON_ERROR`。
关联数组会直接编码为 JSON 对象,而类的实例会编码其所有 `public` 属性。本站 PHP 8.4.27 实测:`['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5]` 编码输出 `{"a":1,"b":2,"c":3,"d":4,"e":5}`;`Emp` 对象经 `strtotime('8/5/1974 12:20:03')` 格式化日期后输出 `{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}`(注意:旧教程中曾出现向 `date()` 第二参数误传字符串的行,PHP 8 强类型下该调用会抛 `TypeError`,必须先经 `strtotime()` 转整数时间戳)。
默认模式下 `json_encode()` 会将中文等非 ASCII 字符转为 `\uXXXX` 转义序列并将斜杠 `/` 转义为 `\/`。添加 `JSON_UNESCAPED_UNICODE` 可保留原生中文,再按位或 `JSON_UNESCAPED_SLASHES` 可保留原生斜杠。本站实测 `['site'=>'蓝色天空','url'=>'https://example.com/php']`:默认编码将中文转为 `\u84dd\u8272\u5929\u7a7a`;加 `JSON_UNESCAPED_UNICODE` 后中文直出;合并 `JSON_UNESCAPED_SLASHES` 后完整输出 `{"site":"蓝色天空","url":"https://example.com/php"}`。
json_decode() 解码类型控制与错误处理
`json_decode($json, $associative = false, $depth = 512, $flags = 0)` 将合法 UTF-8 JSON 字符串还原为 PHP 变量:`$associative` 为 `false`(默认)时把 JSON 对象解为 `stdClass` 实例,为 `true` 时转为关联数组;`$depth` 限定最大递归嵌套层数;`$flags` 常用 `JSON_BIGINT_AS_STRING`(避免超大整数丢失精度)以及 PHP 7.3+ 引入的 `JSON_THROW_ON_ERROR`。
本站 PHP 8.4.27 实测解码 `{"a":1,"b":2,"c":3,"d":4,"e":5}`:默认模式返回 `stdClass` 对象(`$obj->a === 1`),传入 `true` 返回关联数组(`$arr['e'] === 5`);对 30 位大整数启用 `JSON_BIGINT_AS_STRING` 精确保留为字符串 `'123456789012345678901234567890'`。对残缺 JSON `{"a":1` 与超深度嵌套 `[[[1]]]`(`$depth = 2`),`json_decode()` 返回 `null` 并分别记录 `JSON_ERROR_SYNTAX` 与 `JSON_ERROR_DEPTH`,启用 `JSON_THROW_ON_ERROR` 时则直接抛出 `JsonException`。
PHP 核心 JSON 函数清单
| 函数 | 功能说明 |
| json_encode() | 将 UTF-8 编码的 PHP 数组、对象或标量编码为 JSON 字符串,支持位掩码选项控制转义与格式化。 |
| json_decode() | 将 JSON 字符串解码为 PHP `stdClass` 对象(默认)或关联数组(`$associative = true`)。 |
| json_last_error() | 返回最近一次 JSON 编解码的整数错误码(如 `JSON_ERROR_SYNTAX`、`JSON_ERROR_DEPTH`),常配合 `json_last_error_msg()` 使用。 |
运行 PHP 8.4 JSON 编解码、Unicode 标志、大整数与异常处理实验
展开查看收起
<?php
declare(strict_types=1);
date_default_timezone_set('UTC');
class Emp
{
public string $name = '';
public string $hobbies = '';
public string $birthdate = '';
}
$cases = [];
// Case 1: json_encode() for associative array and PHP object
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$e = new Emp();
$e->name = 'sachin';
$e->hobbies = 'sports';
$e->birthdate = date('m/d/Y h:i:s a', strtotime('8/5/1974 12:20:03'));
$actual1 = [
'json_ext_loaded' => extension_loaded('json'),
'array_json' => json_encode($arr),
'object_json' => json_encode($e),
];
$expected1 = [
'json_ext_loaded' => true,
'array_json' => '{"a":1,"b":2,"c":3,"d":4,"e":5}',
'object_json' => '{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}',
];
$cases[] = [
'name' => 'json_encode_array_and_object',
'passed' => $actual1 === $expected1,
'expected' => $expected1,
'actual' => $actual1,
];
// Case 2: Default Unicode escaping vs JSON_UNESCAPED_UNICODE & JSON_UNESCAPED_SLASHES
$cn = ['site' => '蓝色天空', 'url' => 'https://example.com/php'];
$actual2 = [
'default_encoded' => json_encode($cn),
'unescaped_unicode' => json_encode($cn, JSON_UNESCAPED_UNICODE),
'unescaped_both' => json_encode($cn, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
];
$expected2 = [
'default_encoded' => '{"site":"\u84dd\u8272\u5929\u7a7a","url":"https:\/\/example.com\/php"}',
'unescaped_unicode' => '{"site":"蓝色天空","url":"https:\/\/example.com\/php"}',
'unescaped_both' => '{"site":"蓝色天空","url":"https://example.com/php"}',
];
$cases[] = [
'name' => 'json_encode_unescaped_unicode_and_flags',
'passed' => $actual2 === $expected2,
'expected' => $expected2,
'actual' => $actual2,
];
// Case 3: json_decode() returning stdClass vs associative array + JSON_BIGINT_AS_STRING
$jsonStr = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$decodedObj = json_decode($jsonStr, false);
$decodedArr = json_decode($jsonStr, true);
$bigIntJson = '{"id":123456789012345678901234567890}';
$decodedBigInt = json_decode($bigIntJson, true, 512, JSON_BIGINT_AS_STRING);
$actual3 = [
'is_stdclass' => $decodedObj instanceof stdClass,
'obj_a' => $decodedObj->a,
'is_array' => is_array($decodedArr),
'arr_e' => $decodedArr['e'],
'bigint_as_string' => $decodedBigInt['id'],
'bigint_is_string' => is_string($decodedBigInt['id']),
];
$expected3 = [
'is_stdclass' => true,
'obj_a' => 1,
'is_array' => true,
'arr_e' => 5,
'bigint_as_string' => '123456789012345678901234567890',
'bigint_is_string' => true,
];
$cases[] = [
'name' => 'json_decode_object_vs_assoc',
'passed' => $actual3 === $expected3,
'expected' => $expected3,
'actual' => $actual3,
];
// Case 4: json_last_error(), depth limit, and JSON_THROW_ON_ERROR
$broken = '{"a":1';
$brokenVal = json_decode($broken);
$syntaxErrCode = json_last_error();
$deepJson = '[[[1]]]';
$deepVal = json_decode($deepJson, true, 2);
$depthErrCode = json_last_error();
$threwJsonException = false;
try {
json_decode($broken, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $ex) {
$threwJsonException = $ex->getCode() === JSON_ERROR_SYNTAX;
}
$actual4 = [
'broken_returns_null' => $brokenVal === null,
'syntax_error_const' => $syntaxErrCode === JSON_ERROR_SYNTAX,
'depth_returns_null' => $deepVal === null,
'depth_error_const' => $depthErrCode === JSON_ERROR_DEPTH,
'throw_on_error_caught' => $threwJsonException,
];
$expected4 = [
'broken_returns_null' => true,
'syntax_error_const' => true,
'depth_returns_null' => true,
'depth_error_const' => true,
'throw_on_error_caught' => true,
];
$cases[] = [
'name' => 'json_error_handling_and_throw',
'passed' => $actual4 === $expected4,
'expected' => $expected4,
'actual' => $actual4,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
默认情况下 `json_decode('null')` 与解码失败同样返回 `null`,必须再查 `json_last_error() !== JSON_ERROR_NONE` 才能区分;启用 `JSON_THROW_ON_ERROR` 后一旦遇到语法或深度错误会立即抛出 `JsonException`,消除静默失败风险。