萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 中文亂碼完整解決方案:從編碼不一致到實戰轉換函數

在 PHP 與 MySQL 協同開發網站時,瀏覽器輸出中文亂碼幾乎是每位開發者必經的「成人禮」。問題的核心在於三者編碼不一致:HTML 網頁編碼、PHP 檔案編碼、MySQL 資料庫編碼。本文將系統梳理亂碼成因,並提供經實戰驗證的解決方案。

為什麼會出現中文亂碼?

亂碼的本質是字元編碼解碼錯誤。當 PHP 以 UTF-8 讀取資料庫中的 GBK 資料,或網頁宣告 UTF-8 卻輸出 Big5 內容時,瀏覽器便會顯示不可識別的「天書」。常見場景包括:

  • 資料庫儲存編碼與連線編碼不匹配
  • PHP 檔案儲存格式與頁面宣告編碼不同
  • 跨系統對接時(如 SQL Server 使用 GBK)編碼轉換缺失

方案一:PHP 內建 iconv 函數

PHP 提供 iconv() 函數進行字元集轉換,語法如下:

string iconv ( string $in_charset , string $out_charset , string $str )

實際範例:

<?php
$text = "This is the Euro symbol '€'. ";
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
?>

實戰提醒:許多開發者反映 iconv 在特定環境下「無報錯、不轉碼、無輸出」,穩定性不足。

方案二:mb_convert_encoding 實戰轉換

經測試,mb_convert_encoding() 在 GBK/UTF-8 互轉上表現更穩健。核心步驟:

// 檢查擴展是否可用
echo function_exists('mb_convert_encoding');
// 偵測當前編碼
echo mb_detect_encoding($val, "GBK, GB2312, UTF-8");
// 執行轉換:CP936(GBK) → UTF-8
$v = mb_convert_encoding($val, "UTF-8", "CP936");

進階:通用「亂碼克星」函數

為了批次處理資料庫查詢結果集(含陣列、巢狀結構),封裝遞迴轉換函數 auto_charset():

function auto_charset($fContents, $from='gbk', $to='utf-8') {
    $from = strtoupper($from)=='UTF8' ? 'utf-8' : $from;
    $to   = strtoupper($to)=='UTF8'   ? 'utf-8' : $to;
    
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
        return $fContents; // 編碼相同或非字串標量直接返回
    }
    
    if (is_string($fContents)) {
        return function_exists('mb_convert_encoding') 
            ? mb_convert_encoding($fContents, $to, $from) 
            : $fContents;
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key) unset($fContents[$key]);
        }
        return $fContents;
    }
    return $fContents;
}

實際呼叫範例

$arr = array();
while ($list = mssql_fetch_row($row)) {
    $arr[] = $list;
}
$s = auto_charset($arr, 'gbk', 'utf-8');
// 瀏覽器設定 UTF-8 編碼後輸出
print_r($s); die();

最佳實踐總結

  1. 統一編碼:專案啟動前規定資料庫、PHP 檔案、HTML 頁面全站統一使用 UTF-8。
  2. 資料庫連線設定:連線成功後立即執行 SET NAMES utf8。
  3. 輸出控制:在 php.ini 設定 default_charset = "UTF-8" 或程式碼中 header("Content-Type: text/html; charset=utf-8")。
  4. 跨系統對接:使用 auto_charset() 統一轉換外部資料編碼。

掌握編碼流向、善用 mbstring 擴展,中文亂碼不再是難題。

copyright © 萬盛學電腦網 all rights reserved