Blogger Information
Blog 36
fans 4
comment 3
visits 31555
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
7.25  非法字符 原因 以及解决办法
大灰狼的博客
Original
752 people have browsed it

模板文件生成html文件之后会在body开头处加入一个可见的控制符&#65279,导致页面头部会出现一个空白行。原因是页面的编码是UTF-8 + BOM。

    这种编码方式一般会在windows操作系统中出现,比如WINDOWS自带的记事本等软件,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。它是一串隐藏的字符,用于让记事本等编辑器识别这个文件是否以UTF-8编码。对于一般的文件,这样并不会产生什么麻烦。但对于 PHP来说,BOM是个大麻烦。因为PHP并不会忽略BOM,所以在读取、包含或者引用这些文件时,会把BOM作为该文件开头正文的一部分。根据嵌入式语言的特点,这串字符将被直接执行(显示)出来。由此造成即使页面的 top padding 设置为0,也无法让整个网页紧贴浏览器顶部,因为在html一开头有这3个隐藏字符&#65279!

直接notopad++ 保存为无dom格式 (格式-》转为UTF-8 无dom格式)

  然而文件比较多,又想偷懒下,使用下列方法来实现。

  将一下代码保存为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>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!