PHP程序猿应该都知道,对于PHP来说,BOM是一个大麻烦,所以最近就写了一个可以批量移除一个目录下UTF-8文件BOM头的PHP文件,下面分享给大家:)
如果不知道BOM是什么,可以参阅这里:http://baike.baidu.com/subview/126558/5073180.htm#viewPageContent
<?php
/**
* ljfrocky@gmail.com RockyLiang
* 遍历一个目录及其子目录,并去除所有文件头部的BOM
*/
set_time_limit(0);
// 发现BOM时是否自动清除
$auto = true;
// 要遍历的目录,支持相对路径和绝对路径
$base_dir = '.';
recurse_remove_bom($base_dir);
function recurse_remove_bom($path = '.') {
$real_path = realpath($path);
if ($real_path === false) {
echo "[$path] is not exist";
return;
}
if (!is_dir($real_path)) {
echo "[$real_path] is not a directory";
return;
}
$dh = @opendir($real_path);
if ($dh === false) {
echo "Open [$real_path] failed";
return;
}
while (($file = readdir($dh)) !== false) {
if ($file == '.' || $file == '..') {
continue;
}
$sub_dir = $real_path . DIRECTORY_SEPARATOR . $file;
if (is_dir($sub_dir)) {
recurse_remove_bom($sub_dir);
} else {
echo "File : [$sub_dir] " . check_bom($sub_dir) . "<br/>";
}
}
closedir($dh);
}
function check_bom($filename) {
global $auto;
$contents = file_get_contents($filename);
$charset[1] = substr($contents, 0, 1);
$charset[2] = substr($contents, 1, 1);
$charset[3] = substr($contents, 2, 1);
if (ord($charset[1]) == 239
&& ord($charset[2]) == 187
&& ord($charset[3]) == 191) {
if ($auto) {
$rest = substr($contents, 3);
$ret = file_put_contents($filename, $rest, LOCK_EX);
$str = ($ret === false)
? '<font color="red">BOM found, automatically removed failed.</font>'
: '<font color="red">BOM found, automatically removed success.</font>';
return $str;
} else {
return '<font color="red">BOM found.</font>';
}
} else {
return '<font color="green">BOM Not Found.</font>';
}
}
?>