JSON 是現代 Web 數據交換標準。PHP 內建 json_encode/json_decode 提供高效支援,本文詳細說明常用場景與進階技巧。
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
// 解碼為物件 (stdClass)
$obj = json_decode($json);
var_dump($obj->a); // int(1)
// 解碼為關聯數組 (第二參數 true)
$arr = json_decode($json, true);
var_dump($arr['a']); // int(1)
// 陣列編碼為 JSON 字符串
$data = ['a'=>1,'b'=>2,'c'=>3];
echo json_encode($data); // {"a":1,"b":2,"c":3}
?>
json_decode($json, true) 只能將頂層轉為數組,子物件仍為 stdClass。需遞歸轉換:
<?php
function jsonToArrayRecursive($data) {
if (is_object($data)) {
$data = (array) $data;
}
if (is_array($data)) {
return array_map('jsonToArrayRecursive', $data);
}
return $data;
}
$json = '{"webname":"homehf","contact":{"qq":"744348666","mail":"test@163.com"}}';
$obj = json_decode($json);
$arr = jsonToArrayRecursive($obj);
print_r($arr);
/*
Array
(
[webname] => homehf
[contact] => Array
(
[qq] => 744348666
[mail] => test@163.com
)
)
*/
?>
| 常數 | 說明 |
|---|---|
| JSON_HEX_TAG | 將 < > 轉為 \u003C \u003E,防 XSS |
| JSON_HEX_APOS | 轉換單引號 |
| JSON_HEX_QUOT | 轉換雙引號 |
| JSON_HEX_AMP | 轉換 & |
| JSON_UNESCAPED_UNICODE | 不轉義中文等 Unicode 字符(推薦) |
| JSON_UNESCAPED_SLASHES | 不轉義 / |
| JSON_PRETTY_PRINT | 美化輸出,便於調試 |
| JSON_NUMERIC_CHECK | 數字字符串轉為數值類型 |
<?php
// API 輸出標準化
function jsonResponse($data, $code = 200, $msg = '') {
http_response_code($code);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'code' => $code,
'message' => $msg,
'data' => $data
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
// 安全解碼外部輸入
function safeJsonDecode($json, $assoc = true, $depth = 512, $options = 0) {
$result = json_decode($json, $assoc, $depth, $options);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('JSON 解析失敗: ' . json_last_error_msg());
}
return $result;
}
?>
始終檢查 json_last_error(),常見錯誤:JSON_ERROR_SYNTAX(格式錯誤)、JSON_ERROR_UTF8(編碼非 UTF-8)、JSON_ERROR_DEPTH(巢狀過深)。