遷移至 Nginx+PHP-FPM 後報 `Call to undefined function mb_convert_encoding()`,原因是缺少 `mbstring` 擴展。本文對比 `mbstring` 與 `iconv` 兩大編碼轉換庫的安裝、API 差異、效能、邊界處理,給出選型建議。
# 1. 進入原始碼擴展目錄 cd /usr/src/php-5.3.28/ext/mbstring # 2. phpize 生成 configure /usr/local/php/bin/phpize # 3. 配置、編譯、安裝 ./configure --with-php-config=/usr/local/php/bin/php-config make && make install # 4. 啟用擴展 echo 'extension=mbstring.so' >> /usr/local/php/etc/php.ini # 或建議獨立 ini:echo 'extension=mbstring.so' > /usr/local/php/etc/conf.d/mbstring.ini # 5. 重載 PHP-FPM systemctl reload php-fpm
`iconv` 同理:`cd ../iconv && phpize && ./configure --with-iconv=/usr/local --with-php-config=... && make install`。
| 特性 | mb_convert_encoding | iconv |
|---|---|---|
| 所屬擴展 | mbstring | iconv (通常內建) |
| 函式簽名 | `mb_convert_encoding(string $str, string $to, string|null $from=null)` | `iconv(string $from, string $to, string $str)` |
| 自動偵測來源編碼 | 支援 `mb_detect_encoding()` 配合 | 不支援,必須指定 from |
| 非法字元處理 | 預設替換為 `?`,可設 `mb_substitute_character()` | `//IGNORE` 忽略、`//TRANSLIT` 近似轉換 |
| 效能 | 略慢(功能豐富) | 極快(C 底層直接映射) |
| 支援編碼數量 | 100+ | 150+(依系統 libiconv) |
<?php
// GBK → UTF-8
$utf8 = mb_convert_encoding($gbkStr, 'UTF-8', 'GBK');
$utf8 = iconv('GBK', 'UTF-8//IGNORE', $gbkStr); // 推薦加 //IGNORE
// UTF-8 → GBK(含特殊字元如 — · ’)
$gbk = iconv('UTF-8', 'GBK//IGNORE', $utf8); // GBK 比 GB2312 字符集大,建議用 GBK
// Big5 ↔ GB2312
$big5 = mb_convert_encoding($gb2312, 'Big5', 'GB2312');
$gb2312 = iconv('Big5', 'GB2312//IGNORE', $big5);
// 批次轉換陣列
function convertArray(array $data, string $to, string $from): array
{
array_walk_recursive($data, function(& $v) use ($to, $from) {
if (is_string($v)) $v = mb_convert_encoding($v, $to, $from);
});
return $data;
}
?>
編碼問題 90% 來自「源頭不統一」。建立「全鏈路 UTF-8」規範,轉碼只作為邊界兼容手段。