函式名稱:json_decode()
適用版本:PHP 5 >= 5.2.0, PHP 7
函式描述:json_decode() 函式用於將 JSON 格式的字串轉換為 PHP 變數。
用法: json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0): mixed
引數:
- $json (必需):要解碼的 JSON 字串。
- $assoc (可選):當該引數為 true 時,將返回關聯陣列;當該引數為 false 時,將返回物件。預設為 false。
- $depth (可選):指定最大解碼深度。預設為 512。
- $options (可選):指定解碼選項。預設為 0。
返回值: 解碼成功時,將返回解碼後的 PHP 變數。解碼失敗時,將返回 null。
示例:
解碼 JSON 字串為物件: $json_str = '{"name":"John", "age":30, "city":"New York"}'; $obj = json_decode($json_str); echo $obj->name; // 輸出:John
解碼 JSON 字串為關聯陣列: $json_str = '{"name":"John", "age":30, "city":"New York"}'; $arr = json_decode($json_str, true); echo $arr["name"]; // 輸出:John
解碼包含巢狀陣列的 JSON 字串: $json_str = '{"name":"John", "age":30, "cities":["New York", "London", "Paris"]}'; $obj = json_decode($json_str); echo $obj->cities[0]; // 輸出:New York
解碼 JSON 字串時設定解碼選項: $json_str = '{"name":"John", "age":30, "city":"New York"}'; $obj = json_decode($json_str, false, 512, JSON_BIGINT_AS_STRING); echo $obj->age; // 輸出:"30"(作為字串型別輸出)
注意事項:
- 該函式僅適用於解碼 JSON 字串,如果要將 PHP 變數編碼為 JSON 字串,需要使用 json_encode() 函式。
- 如果 JSON 字串解碼失敗,將返回 null。可以透過使用 json_last_error() 和 json_last_error_msg() 函式獲取解碼錯誤的詳細資訊。
- 在 PHP 7 中,該函式支援解碼更大深度的 JSON 字串,預設為 512。在 PHP 5 中,預設深度為 128。可以透過修改 $depth 引數來自定義解碼深度。
- 可以透過設定解碼選項來改變解碼行為,例如將大整數作為字串型別輸出(JSON_BIGINT_AS_STRING)。
- JSON 字串中的特殊字元(如斜槓、引號等)將自動進行轉義。