php,thinkphp出现BOM(字符)出现的原因以及解决方法

今天在项目中发现,客户端在使用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文件放到根目录下,执行一下,即可自动完成转换。

代码如下:

<?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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值