函数名:json_encode()
适用版本:PHP 5 >= 5.2.0, PHP 7
用法:json_encode(mixed $value, int $options = 0, int $depth = 512): string|false
参数:
返回值:
示例:
$arr = array('apple', 'banana', 'orange');
$json = json_encode($arr);
echo $json;
// 输出:["apple","banana","orange"]
$arr = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$json = json_encode($arr, JSON_PRETTY_PRINT);
echo $json;
// 输出:
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }
$str = "This is a \"quoted\" string.";
$json = json_encode($str);
echo $json;
// 输出:"This is a \"quoted\" string."
$str = "Hello, 世界!";
$json = json_encode($str, JSON_UNESCAPED_UNICODE);
echo $json;
// 输出:"Hello, 世界!"
注意:json_encode() 函数在编码过程中,会自动将非 UTF-8 编码的字符串转换为 UTF-8。如果编码过程中遇到无法转换的字符,将会返回 false。