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數據的操作。