阅读量:2
在PHP中,可以使用内置的json_encode()
函数将PHP数组或对象转换为JSON字符串,使用json_decode()
函数将JSON字符串解析为PHP数组或对象。
下面是一些例子来演示如何解析和生成JSON数据:
- 将PHP数组转换为JSON字符串:
$data = array("name" => "John", "age" => 30, "city" => "New York"); $jsonData = json_encode($data); echo $jsonData;
输出:
{"name":"John","age":30,"city":"New York"}
- 将PHP对象转换为JSON字符串:
class Person { public $name; public $age; public $city; } $person = new Person(); $person->name = "John"; $person->age = 30; $person->city = "New York"; $jsonData = json_encode($person); echo $jsonData;
输出:
{"name":"John","age":30,"city":"New York"}
- 解析JSON字符串为PHP数组:
$jsonData = '{"name":"John","age":30,"city":"New York"}'; $data = json_decode($jsonData, true); print_r($data);
输出:
Array ( [name] => John [age] => 30 [city] => New York )
- 解析JSON字符串为PHP对象:
$jsonData = '{"name":"John","age":30,"city":"New York"}'; $person = json_decode($jsonData); echo $person->name; echo $person->age; echo $person->city;
输出:
John 30 New York
注意:json_encode()
函数接受一个可选的参数来控制生成的JSON字符串的格式,如缩进和排序等。json_decode()
函数也接受一个可选的参数来指定解析的JSON字符串的行为,如返回数组还是对象等。