在PHP中使用JSON進行數(shù)據(jù)交換非常簡單
<?php
$data = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
// 將數(shù)組轉(zhuǎn)換為JSON字符串
$json_data = json_encode($data);
echo $json_data; // 輸出: {"name":"John","age":30,"city":"New York"}
?>
<?php
$json_string = '{"name":"John","age":30,"city":"New York"}';
// 將JSON字符串轉(zhuǎn)換為數(shù)組
$data = json_decode($json_string, true);
print_r($data); // 輸出: Array ( [name] => John [age] => 30 [city] => New York )
?>
<?php
// 假設(shè)有一個名為data.json的文件,其中包含以下內(nèi)容:
// {"name":"John","age":30,"city":"New York"}
// 從文件中讀取JSON數(shù)據(jù)
$json_string = file_get_contents('data.json');
// 將JSON字符串解析為數(shù)組
$data = json_decode($json_string, true);
print_r($data); // 輸出: Array ( [name] => John [age] => 30 [city] => New York )
?>
<?php
$data = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
// 將數(shù)組轉(zhuǎn)換為JSON字符串
$json_data = json_encode($data);
// 將JSON字符串寫入文件
file_put_contents('data.json', $json_data);
?>
這些示例展示了如何在PHP中使用JSON進行數(shù)據(jù)交換。你可以根據(jù)需要調(diào)整這些代碼片段以適應(yīng)你的項目。