PHP 5.2+ 內建 `json_encode()`,但預設將非 ASCII 字元(含中文)轉為 Unicode 逃逸序列(如 `\u4e2d\u6587`),雖符合 JSON 標準,但在某些舊系統、日誌檢視、前端直接讀取時造成「亂碼」困擾。
<?php
$array = array('name' => '希亞', 'age' => 20, 'city' => '台北');
// PHP 5.4+ 直接支援
$json = json_encode($array, JSON_UNESCAPED_UNICODE);
echo $json;
// {"name":"希亞","age":20,"city":"台北"}
// 組合旗標:不轉義斜線 + 不轉義 Unicode
$json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
原理:先將所有字串值 `urlencode()` 編碼(中文變 `%E4%B8%AD%E6%96%87`),`json_encode` 後再 `urldecode()` 還原。
<?php
function array_recursive(&$array, $func, $apply_to_keys = false) {
static $depth = 0;
if (++$depth > 1000) die('遞迴過深,可能死迴圈');
foreach ($array as $key => &$value) {
if (is_array($value)) {
array_recursive($value, $func, $apply_to_keys);
} else {
$value = $func($value);
}
if ($apply_to_keys && is_string($key)) {
$new_key = $func($key);
if ($new_key !== $key) {
$array[$new_key] = $value;
unset($array[$key]);
}
}
}
$depth--;
}
function json_encode_chinese($array) {
array_recursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
// 使用
$array = array('name' => '希亞', 'age' => 20, 'tags' => array('PHP', 'JSON', '中文'));
echo json_encode_chinese($array);
// {"name":"希亞","age":20,"tags":["PHP","JSON","中文"]}
class ChineseJSONEncoder {
public static function encode($data, $flags = 0) {
if (PHP_VERSION_ID >= 50400) {
return json_encode($data, $flags | JSON_UNESCAPED_UNICODE);
}
// PHP 5.2/5.3 降級處理
return self::encodeLegacy($data);
}
private static function encodeLegacy($data) {
if (is_array($data)) {
$is_list = array_keys($data) === range(0, count($data) - 1);
$parts = array();
foreach ($data as $k => $v) {
$encoded_v = self::encodeLegacy($v);
if ($is_list) {
$parts[] = $encoded_v;
} else {
$parts[] = self::encodeLegacy($k) . ':' . $encoded_v;
}
}
return $is_list ? '[' . implode(',', $parts) . ']'
: '{' . implode(',', $parts) . '}';
}
if (is_string($data)) {
// 手動處理逃逸,但保留 Unicode 字元
return '"' . addcslashes($data, "\0..\37\"\\") . '"';
}
if (is_bool($data)) return $data ? 'true' : 'false';
if (is_null($data)) return 'null';
if (is_numeric($data)) return (string)$data;
return 'null';
}
}
<?php
// 現代寫法(PDO + JSON_UNESCAPED_UNICODE)
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass');
$stmt = $pdo->query('SELECT id, name, email FROM users LIMIT 10');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'total' => count($users),
'results' => $users
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
| 旗標 | 說明 | PHP 版本 |
|---|---|---|
JSON_UNESCAPED_UNICODE | 不將 Unicode 字元轉為 \uXXXX | 5.4+ |
JSON_UNESCAPED_SLASHES | 不轉義 /(預設會變 \/) | 5.4+ |
JSON_NUMERIC_CHECK | 數字字串轉為數值型別 | 5.3+ |
JSON_PRETTY_PRINT | 美化輸出(縮排換行) | 5.4+ |
JSON_PRESERVE_ZERO_FRACTION | 保留浮點數 .0(如 1.0 不變 1) | 5.6+ |
JSON_THROW_ON_ERROR | 錯誤時拋出例外而非回傳 false | 7.3+ |
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
// PHP 7.3+ 會自動拋出 JsonException
// 手動檢查(舊版相容)
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('JSON 編碼錯誤: ' . json_last_error_msg());
}