解决方法:
把头部BOM的3个字节信息识别出来,然后剔除掉。不过一般情况我们不知道哪个文件有BOM,或者是有很多文件,这个时候,就需要进行批量处理了,下面代码主要就是展现了批量处理的情况,应该会对大家工作中有帮助。
方法:
设置一个路径,然后直接执行就行。 代码如下:
PHP
// 设定你要清除BOM的根目录(会自动扫描所有子目录和文件)
$HOME = dirname(__FILE__);
// 如果是Windows系统,修改为:$WIN = 1;
$WIN = 0;
?>
UTF8 BOM 清除器
PHP
$BOMBED = array();
RecursiveFolder($HOME);
echo '
// 递归扫描
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,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
return false;
}
?>
// 设定你要清除BOM的根目录(会自动扫描所有子目录和文件)
$HOME = dirname(__FILE__);
// 如果是Windows系统,修改为:$WIN = 1;
$WIN = 0;
?>
PHP
$BOMBED = array();
RecursiveFolder($HOME);
echo '
These files had UTF8 BOM,but i cleaned them:
foreach ($BOMBED as $utf) { echo $utf ."
\n"; }
echo '
// 递归扫描
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,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
return false;
}
?>