在PHP中,可以使用內置的json_encode()
函數將PHP數組或對象轉換為JSON字符串,使用json_decode()
函數將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"}
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"}
$jsonData = '{"name":"John","age":30,"city":"New York"}';
$data = json_decode($jsonData, true);
print_r($data);
輸出:
Array
(
[name] => John
[age] => 30
[city] => New York
)
$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字符串的行為,如返回數組還是對象等。