phpBOM頭(字符)出現的原因以及解決方法_PHP程序員博客|高蒙個人博客


今天在項目中發現,客戶端在使用ajax得到返回值時,無法匹配字符串。總是報錯,打開頁面接口發現,頁面的頭部出現了的字符(BOM頭),找到問題了,那么直接用代碼清除掉即可。

php隱形字符&#65279解釋如下:

UTF-8 編碼的文件可以分為無 BOM 和 BOM 兩種格式。

何謂BOM?

  •   "EF BB BF" 這三個字節就叫BOM,全稱是"Byte Order Mard"。在utf8文件中常用BOM來表明這個文件是UTF-8文件,而BOM的本意是在utf16中用。

  •   utf-8文件在php中輸出的時候bom是會被輸出的,所以要在php中使用utf-8,必須要是使用不帶bom頭的utf-8文件。

  •   常用的文本編輯軟件對utf-8文件保存的支持方式並不一樣,使用的時候要特別留意。

解決的方法:

1、接notopad++ 保存為無dom格式(格式->轉為UTF-8 無dom格式),適合文件少的情況。

2、文件比較多,又想偷懶下,使用下列方法來實現(親測可用)。將一下代碼保存為a.php文件放到根目錄下,執行一下,即可自動完成轉換。

代碼如下:

  1. <?php 
  2. // 設定你要清除BOM的根目錄(會自動掃描所有子目錄和文件)
  3. $HOME = dirname(__FILE__);
  4. // 如果是Windows系統,修改為:$WIN = 1;
  5. $WIN = 0;
  6. ?>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  8. <html xmlns="http://www.w3.org/1999/xhtml">
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  11. <title>UTF8 BOM 清除器</title>
  12. <style>
  13. body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
  14. .FOUND { color: #F30; font-size: 14px; font-weight: bold; }
  15. </style>
  16. </head>
  17. <body>
  18. <?php
  19. $BOMBED = array();
  20. RecursiveFolder($HOME);
  21. echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
  22. foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
  23. echo '</p>';
  24. // 遞歸掃描
  25. function RecursiveFolder($sHOME) {
  26.  global $BOMBED, $WIN;
  27.  $win32 = ($WIN == 1) ? "\\" : "/";
  28.  $folder = dir($sHOME);
  29.  $foundfolders = array();
  30.  while ($file = $folder->read()) {
  31.   if($file != "." and $file != "..") {
  32.    if(filetype($sHOME . $win32 . $file) == "dir"){
  33.     $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
  34.    } else {
  35.     $content = file_get_contents($sHOME . $win32 . $file);
  36.     $BOM = SearchBOM($content);
  37.     if ($BOM) {
  38.      $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;
  39.      // 移出BOM信息
  40.      $content = substr($content,3);
  41.      // 寫回到原始文件
  42.      file_put_contents($sHOME . $win32 . $file, $content);
  43.     }
  44.    }
  45.   }
  46.  }
  47.  $folder->close();
  48.  if(count($foundfolders) > 0) {
  49.   foreach ($foundfolders as $folder) {
  50.    RecursiveFolder($folder, $win32);
  51.   }
  52.  }
  53. }
  54. // 搜索當前文件是否有BOM
  55. function SearchBOM($string) { 
  56.   if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
  57.   return false; 
  58. }
  59. ?>
  60. </body>
  61. </html>

 

如果您對上面的內容還有補充,請在文章下評論或者給我 [留言]。謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM