UTF-8 編碼的檔案若包含 BOM(Byte Order Mark,位元組順序標記),會導致 PHP 輸出時在最前方出現不可見字元,進而干擾 HTTP Header 送出、JSON 格式破壞、XML 解析失效等問題。本文提供完整的偵測與移除程式碼,可整合至專案部署流程中。
UTF-8 BOM 為三個位元組:EF BB BF(十進位 239, 187, 191),位於檔案最開頭。
<?php
/**
* 檢查並移除檔案開頭的 UTF-8 BOM
* @param string $filename 檔案路徑
* @return bool 成功移除回傳 true,無 BOM 或失敗回傳 false
*/
function removeBOM($filename) {
$contents = file_get_contents($filename);
if ($contents === false) return false;
// 檢查前三個位元組
if (strlen($contents) >= 3 &&
ord($contents[0]) === 239 &&
ord($contents[1]) === 187 &&
ord($contents[2]) === 191) {
// 移除前三個位元組並覆寫檔案
$rest = substr($contents, 3);
return file_put_contents($filename, $rest) !== false;
}
return false; // 無 BOM
}
/**
* 批次處理目錄下所有 PHP 檔案
*/
function cleanDirectoryBOM($dir) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
if (removeBOM($file->getPathname())) {
echo "已移除 BOM: {$file->getPathname()}\n";
}
}
}
}
// 使用範例
// removeBOM('config.php');
// cleanDirectoryBOM(__DIR__ . '/src');
cleanDirectoryBOM,確保上線程式碼無 BOM。.gitattributes 強制 eol=lf 與無 BOM。| 症狀 | 可能原因 |
|---|---|
| 頁面頂端多出空白行或亂碼 | 包含檔案有 BOM |
header() 警告 "Cannot modify header information" | BOM 導致輸出提前 |
json_decode 回傳 null / JSON.parse 失敗 | BOM 破壞 JSON 格式 |
| XML 解析錯誤 "XML declaration not at start" | BOM 佔據檔案開頭 |
妥善處理 BOM,能避免許多難以追蹤的詭異錯誤,建議納入專案規範與 CI 流程中。