phpBOM头(字符)出现的原因以及解决方法

今天在项目中发现,客户端在使用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>

猜你喜欢

转载自blog.csdn.net/hyb1234hi/article/details/80424354