阅读量:0
json_encode()
是 PHP 中用于将数组或对象转换为 JSON 格式的字符串的函数。以下是如何使用 json_encode()
实现数据格式转换的示例:
- 将关联数组转换为 JSON 字符串:
<?php $assoc_array = array( "name" => "John", "age" => 30, "city" => "New York" ); $json_string = json_encode($assoc_array); echo $json_string; ?>
输出:
{"name":"John","age":30,"city":"New York"}
- 将多维数组转换为 JSON 字符串:
<?php $multi_dim_array = array( array( "name" => "John", "age" => 30, "city" => "New York" ), array( "name" => "Jane", "age" => 28, "city" => "San Francisco" ) ); $json_string = json_encode($multi_dim_array); echo $json_string; ?>
输出:
[ {"name":"John","age":30,"city":"New York"}, {"name":"Jane","age":28,"city":"San Francisco"} ]
- 将对象转换为 JSON 字符串:
<?php class Person { public $name; public $age; public $city; public function __construct($name, $age, $city) { $this->name = $name; $this->age = $age; $this->city = $city; } } $person = new Person("John", 30, "New York"); $json_string = json_encode($person); echo $json_string; ?>
输出:
{"name":"John","age":30,"city":"New York"}
注意:json_encode()
函数在处理特殊字符(如非 ASCII 字符)时可能会返回 null
或抛出警告。为了避免这些问题,可以使用 JSON_UNESCAPED_UNICODE
选项来保留 Unicode 字符:
<?php $json_string = json_encode($assoc_array, JSON_UNESCAPED_UNICODE); echo $json_string; ?>
输出:
{"name":"John","age":30,"city":"纽约"}