JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛应用于Web开发。它基于JavaScript对象表示法,便于在各种语言中处理和传输数据。
PHP提供了json_decode函数,可以将JSON字符串转换为PHP数组。只需将第二个参数设为true即可实现数组转换。
$json_string = '{"name": "John", "age": 30, "city": "New York"}'; $data = json_decode($json_string, true); print_r($data);
输出结果:
Array ( [name] => John [age] => 30 [city] => New York )
如果需要将JSON字符串转换为PHP对象,可以省略json_decode的第二个参数,默认返回对象形式。
$json_string = '{"name": "John", "age": 30, "city": "New York"}'; $data = json_decode($json_string); echo $data->name; // 输出 John
当JSON数据存储在文件中时,可以先使用file_get_contents函数读取文件内容,然后用json_decode进行转换。
$json_string = file_get_contents('data.json'); $data = json_decode($json_string, true);
PHP提供json_encode函数,将数组或对象转换为JSON格式字符串,方便数据传输或存储。
$data = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); $json_string = json_encode($data); echo $json_string; // 输出:{"name":"John","age":30,"city":"New York"}
默认情况下,json_encode会对Unicode字符进行转义。使用JSON_UNESCAPED_UNICODE选项,可以保持Unicode字符不被转义,方便中文等字符的显示。
$data = array( 'name' => '张三', 'age' => 30, 'city' => '北京' ); $json_string = json_encode($data, JSON_UNESCAPED_UNICODE); echo $json_string; // 输出:{"name":"张三","age":30,"city":"北京"}
在PHP中,使用json_decode和json_encode函数可以轻松实现JSON与数组或对象之间的转换,支持从文件读取数据和处理Unicode字符,极大地方便了Web应用中JSON数据的操作。