PHP 中解析 JSON 有两种方法:json_decode() 函数:将 JSON 字符串转换为 PHP 数组。json_parse() 函数:直接解析 JSON 字符串并返回解析后的数据,通常是一个关联数组。

如何解析 JSON
在 PHP 中,可以使用两种主要方法来解析 JSON:
1. json_decode() 函数
json_decode() 函数用于将 JSON 字符串转换为 PHP 数组。它采用一个 JSON 字符串作为参数并返回一个包含解析后的数据的数组。
立即学习“PHP免费学习笔记(深入)”;
语法:
<code class="php">$php_array = json_decode($json_string);</code>
示例:
<code class="php">$json_string = '{"name": "John Doe", "age": 30, "city": "New York"}';
$php_array = json_decode($json_string);
var_dump($php_array);
// 输出:array(3) { ["name"]=> string(7) "John Doe" ["age"]=> int(30) ["city"]=> string(8) "New York" }</code>2. json_parse() 函数
json_parse() 函数是 JSON 解析的底层函数,它直接解析 JSON 字符串并返回解析后的数据。
语法:
<code class="php">$php_array = json_parse($json_string);</code>
示例:
<code class="php">$json_string = '{"name": "John Doe", "age": 30, "city": "New York"}';
$php_array = json_parse($json_string);
var_dump($php_array);
// 输出:{
// "name": "John Doe",
// "age": 30,
// "city": "New York"
// }</code>两者的区别
-
json_decode()返回一个 PHP 数组,而json_parse()直接返回解析后的数据,通常是一个关联数组。 -
json_decode()可以处理具有 Unicode 转义字符和其他特殊字符的 JSON 字符串,而json_parse()则不能。 -
json_parse()仅适用于处理有效的 JSON 字符串,而json_decode()可以尝试从无效的 JSON 字符串中提取数据。











