json_encode 預設輸出緊湊、中文轉 Unicode (\u4e2d\u6587)、無縮排,人類難以閱讀。
<?php
function jsonFormat($data, $indent = ' ') {
// 1. 遞歸 urlencode 保護中文
$encode = function($v) use (&$encode) {
if (is_array($v)) return array_map($encode, $v);
if (is_string($v)) return urlencode($v);
return $v;
};
$data = $encode($data);
// 2. json_encode (JSON_UNESCAPED_SLASHES 保持 / 不轉義)
$json = json_encode($data, JSON_UNESCAPED_SLASHES);
// 3. urldecode 還原中文
$json = urldecode($json);
// 4. 手動縮排美化
$result = ''; $level = 0; $inString = false; $escaped = false;
$len = strlen($json);
for ($i = 0; $i < $len; $i++) {
$ch = $json[$i];
if ($inString) {
$result .= $ch;
if ($escaped) { $escaped = false; continue; }
if ($ch === '\\') { $escaped = true; continue; }
if ($ch === '"') { $inString = false; continue; }
continue;
}
if ($ch === '"') { $inString = true; $result .= $ch; continue; }
if ($ch === '{' || $ch === '[') {
$result .= $ch . "\n" . str_repeat($indent, ++$level);
continue;
}
if ($ch === '}' || $ch === ']') {
$result .= "\n" . str_repeat($indent, --$level) . $ch;
continue;
}
if ($ch === ',') { $result .= ",\n" . str_repeat($indent, $level); continue; }
if ($ch === ':') { $result .= ": "; continue; }
$result .= $ch;
}
return $result;
}
// 使用
$arr = ['status'=>true, 'member'=>[['name'=>'李逍遙','gender'=>'男'],['name'=>'趙靈兒','gender'=>'女']]];
echo jsonFormat($arr);
{
"status": true,
"member": [
{
"name": "李逍遙",
"gender": "男"
},
{
"name": "趙靈兒",
"gender": "女"
}
]
}
// PHP 5.4+ 支援 JSON_PRETTY_PRINT + JSON_UNESCAPED_UNICODE
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
JSON_PRETTY_PRINT:自動縮排換行。JSON_UNESCAPED_UNICODE:中文直接輸出不轉義 (PHP 5.4+)。JSON_UNESCAPED_SLASHES:/ 不轉義為 \/。PHP 5.4+ 專案直接使用 json_encode 三旗標即可獲得完美格式化輸出;舊版本或需自訂縮排字元時,jsonFormat 函數提供純 PHP 實現的備選方案。調試 API、記錄日誌時,美化 JSON 能大幅提升排查效率。