推荐答案
// www.javascriptcn.com code example
// json_encode 示例
$data = array("name" => "John", "age" => 30, "city" => "New York");
$jsonString = json_encode($data);
echo $jsonString; // 输出: {"name":"John","age":30,"city":"New York"}
// json_decode 示例
$jsonString = '{"name":"John","age":30,"city":"New York"}';
$data = json_decode($jsonString, true);
print_r($data); // 输出: Array ( [name] => John [age] => 30 [city] => New York )本题详细解读
json_encode 函数
json_encode 函数用于将 PHP 数组或对象转换为 JSON 格式的字符串。它的基本语法如下:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
- $value: 要编码的值,通常是数组或对象。
- $options: 可选参数,用于指定编码时的行为。常见的选项包括
JSON_PRETTY_PRINT(格式化输出)、JSON_UNESCAPED_UNICODE(不转义 Unicode 字符)等。 - $depth: 可选参数,指定最大递归深度。
json_decode 函数
json_decode 函数用于将 JSON 格式的字符串解码为 PHP 数组或对象。它的基本语法如下:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
- $json: 要解码的 JSON 字符串。
- $assoc: 可选参数,如果为
true,则将 JSON 对象解码为关联数组;如果为false,则解码为对象。 - $depth: 可选参数,指定最大递归深度。
- $options: 可选参数,用于指定解码时的行为。常见的选项包括
JSON_BIGINT_AS_STRING(将大整数作为字符串处理)等。
注意事项
- 编码时的数据类型:
json_encode只能编码 UTF-8 编码的数据。如果数据包含非 UTF-8 字符,可能会导致编码失败。 - 解码时的数据类型:
json_decode默认将 JSON 对象解码为 PHP 对象。如果需要解码为关联数组,应将$assoc参数设置为true。 - 错误处理:如果
json_encode或json_decode失败,可以使用json_last_error()函数获取错误信息。
通过合理使用 json_encode 和 json_decode,可以方便地在 PHP 和 JSON 数据格式之间进行转换,适用于 API 开发、数据存储等场景。