早期 PHP 4/5.0 無 mbstring、iconv 時,需手動將中文字元組裝為 UTF-8 位元組序列(數值實體 XXX;)以正確顯示。本文保留該經典實作供參考,**現代專案請直接用 mb_convert_encoding 或確保全端 UTF-8**。
<?php
/**
* 將 UTF-8 字串轉為數值實體 (XXX;)
* 僅供教學/極舊環境參考
*/
function htou(string $c): int
{
// $c 應為 3 位元組 UTF-8 字元
$n = (ord($c[0]) & 0x1F) << 12;
$n += (ord($c[1]) & 0x3F) << 6;
$n += ord($c[2]) & 0x3F;
return $n;
}
function utf8_to_entities(string $str): string
{
$encode = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$byte = ord($str[$i]);
if ($byte > 0xA0) { // 多位元組字元 (簡易判斷)
$entity = htou(substr($str, $i, 3));
$encode .= '' . $entity . ';';
$i += 2;
} else {
$encode .= '' . $byte . ';';
}
}
return $encode;
}
// 測試
echo utf8_to_entities('測試'); // 测试
?>
htou() 解析 3 位元組 UTF-8 還原 Unicode 碼位:(b1&0x1F)<<12 | (b2&0x3F)<<6 | (b3&0x3F)。codepoint; 數值實體,瀏覽器自動渲染對應字元。<?php
// 1. 內部編碼統一
mb_internal_encoding('UTF-8');
// 2. 任意編碼互轉
$utf8 = mb_convert_encoding($sourceStr, 'UTF-8', 'Big5'); // Big5 → UTF-8
$utf8 = mb_convert_encoding($sourceStr, 'UTF-8', 'GBK'); // GBK → UTF-8
$utf8 = mb_convert_encoding($sourceStr, 'UTF-8', 'auto'); // 自動偵測
// 3. 輸出數值實體 (極少數舊系統需求)
function toNumericEntities(string $utf8): string
{
return mb_encode_numericentity($utf8, [0x0, 0x10FFFF, 0, 0xFFFF], 'UTF-8');
}
echo toNumericEntities('測試'); // 测试
// 4. JSON 輸出中文不轉義
echo json_encode(['msg' => '中文'], JSON_UNESCAPED_UNICODE); // {"msg":"中文"}
?>
手動位元組組裝是理解 UTF-8 內部結構的好教材,**生產環境請務必使用 mbstring/iconv 內建函數**,並確保「資料庫 → PHP → HTML → 瀏覽器」全鏈路 UTF-8 一致,徹底杜絕編碼問題。