如何使用PHP批量去除檔案UTF8 BOM資訊_php技巧

來源:互聯網
上載者:User

原理:
UTF8檔案,微軟為了增加一個識別資訊,有了BOM這個東西:BOM —— Byte Order Mark,預設在Windows等平台上編輯的UTF8檔案會在頭部增加3個位元組的標記資訊,我們PHP引擎在處理的時候會完整讀取整個PHP代碼文檔, 如果PHP檔案頭部包含BOM資訊,就會輸出一個空白,在很多時候會帶來問題,比如我們session無法工作、cookie無法設定等等問題。

解決方案:
把頭部BOM的3個位元組資訊識別出來,然後剔除掉。不過一般情況我們不知道哪個檔案有BOM,或者是有很多檔案,這個時候,就需要進行批量處理了,下面代碼主要就是展現了批量處理的情況,應該會對大家工作中有協助。

執行方法:
設定一個路徑,然後直接執行就行。

複製代碼 代碼如下:

<?php
// 設定你要清除BOM的根目錄(會自動掃描所有子目錄和檔案)
$HOME = dirname(__FILE__);
// 如果是Windows系統,修改為:$WIN = 1;
$WIN = 0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF8 BOM 清除器</title>
<style>
body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
.FOUND { color: #F30; font-size: 14px; font-weight: bold; }
</style>
</head>
<body>
<?php
$BOMBED = array();
RecursiveFolder($HOME);
echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
echo '</p>';
// 遞迴掃描
function RecursiveFolder($sHOME) {
 global $BOMBED, $WIN;
 $win32 = ($WIN == 1) ? "\\" : "/";
 $folder = dir($sHOME);
 $foundfolders = array();
 while ($file = $folder->read()) {
  if($file != "." and $file != "..") {
   if(filetype($sHOME . $win32 . $file) == "dir"){
    $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
   } else {
    $content = file_get_contents($sHOME . $win32 . $file);
    $BOM = SearchBOM($content);
    if ($BOM) {
     $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;
     // 移出BOM資訊
     $content = substr($content,3);
     // 寫回到原始檔案
     file_put_contents($sHOME . $win32 . $file, $content);
    }
   }
  }
 }
 $folder->close();
 if(count($foundfolders) > 0) {
  foreach ($foundfolders as $folder) {
   RecursiveFolder($folder, $win32);
  }
 }
}
// 搜尋當前檔案是否有BOM
function SearchBOM($string) {
  if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
  return false;
}
?>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.