瀏覽器解碼編碼與伺服器輸出編碼不一致。常見編碼:UTF-8 (國際標準)、Big5/GB2312 (繁/簡中舊系統)。
header('Content-Type: text/html; charset=utf-8'); (必須在任何輸出前)。<meta charset="utf-8"> (HTML5 寫法) 或 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">。<?php
// PDO
$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", $user, $pass);
// mysqli
$mysqli->set_charset('utf8mb4');
?>
# Linux/Mac: 將目錄下所有 .php 轉為 UTF-8 無 BOM
find . -name "*.php" -exec sh -c 'iconv -f BIG5 -t UTF-8 "$1" > "$1.tmp" && mv "$1.tmp" "$1"' _ {} \;
# 或使用 PHP 腳本遞迴轉碼
| 原因 | 檢查方法 | 解決 |
|---|---|---|
| PHP 語法錯誤/致命錯誤 | 查看錯誤日誌 /var/log/php-fpm/error.log 或 nginx/error.log | 修正代碼錯誤 (少分號、未定義函數、類別不存在) |
display_errors = Off | 臨時在檔案頂部加 ini_set('display_errors',1); error_reporting(E_ALL); | 開發環境開啟錯誤顯示,生產環境只記錄日誌 |
| 輸出緩衝區未刷新 | 代碼中有 ob_start() 但無 ob_end_flush() | 補全緩衝區結束或移除不必要的 ob_start() |
| HTTP 標頭已發送 | 錯誤訊息 "Cannot modify header information - headers already sent" | 確保 header()/session_start()/setcookie() 在任何輸出 (含空白、BOM) 前呼叫 |
| 記憶體耗盡 | 日誌出現 "Allowed memory size exhausted" | 調高 memory_limit 或優化代碼 (分批處理、生成器) |
| 無限迴圈/死鎖 | 請求長時間無回應,最終逾時 | 檢查迴圈條件、資料庫鎖、外部 API 無超時設定 |
| 編碼儲存問題 (另存新檔技巧) | 另存為 .txt → 改編碼 → 改回 .php | 這是編輯器編碼標記錯誤導致,重新儲存可修正 |
dump()/dd() 更美觀)。charset=utf8mb4 (資料庫、連線、HTML、PHP header)display_errors=On、生產環境 log_errors=On, display_errors=Off<?php 前不可有任何字元)