PHP的json_decode()函數(shù)用于將JSON格式的字符串轉(zhuǎn)換為PHP變量。它的語法是:
mixed json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
參數(shù)說明:
示例用法:
$jsonString = '{"name":"John", "age":30, "city":"New York"}';
$decodedData = json_decode($jsonString);
// 訪問解碼后的數(shù)據(jù)
echo $decodedData->name; // 輸出:John
echo $decodedData->age; // 輸出:30
echo $decodedData->city; // 輸出:New York
// 將返回的數(shù)據(jù)轉(zhuǎn)換為關(guān)聯(lián)數(shù)組
$decodedDataArray = json_decode($jsonString, true);
echo $decodedDataArray['name']; // 輸出:John
echo $decodedDataArray['age']; // 輸出:30
echo $decodedDataArray['city']; // 輸出:New York
需要注意的是,如果JSON字符串無法解碼,則json_decode()函數(shù)會(huì)返回null。可以使用json_last_error()函數(shù)獲取解碼過程中的錯(cuò)誤信息。