什么是bom头?
在utf-8编码文件中bom在文件头部,占用三个字节,用来标示该文件属于utf-8编码,现在已经有很多软件识别bom头,但是还有些不能识别bom头,比如php就不能识别bom头,这也是用记事本编辑utf-8编码后执行就会出错的原因了。
批量去除bom头代码如下所示:
<?php
if (isset($_get['dir'])){ //设置文件目录
$basedir=$_get['dir'];
}else{
$basedir = '.';
}
$auto = 1;
checkdir($basedir);
function checkdir($basedir){
if ($dh = opendir($basedir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..'){
if (!is_dir($basedir."/".$file)) {
echo "filename: $basedir/$file ".checkbom("$basedir/$file")." <br>";
}else{
$dirname = $basedir."/".$file;
checkdir($dirname);
}
}
}
closedir($dh);
}
}
function checkbom ($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 == 1) {
$rest = substr($contents, 3);
rewrite ($filename, $rest);
return ("<font color=red>bom found, automatically removed._<a href=http://www.joyphper.net>http://www.joyphper.net</a></font>");
} else {
return ("<font color=red>bom found.</font>");
}
}
else return ("bom not found.");
}
function rewrite ($filename, $data) {
$filenum = fopen($filename, "w");
flock($filenum, lock_ex);
fwrite($filenum, $data);
fclose($filenum);
}
?>
ps:去掉bom头的办法,简单的是下面两种:
1、editplus去bom头的方法
编辑器调整为utf8编码格式后,保存的文件前面会多出一串隐藏的字符(也即是bom),用于编辑器识别这个文件是否是以utf8编码。
运行editplus,点击工具,选择首选项,选中文件,utf-8标识选择 总是删除签名,
然后对php文件编辑和保存后的php文件就是不带bom的了。
2、ultraedit去除bom头办法
打开文件后,另存为选项的编码格式里选择(utf-8 无bom头),确定就ok了
怎么样,去掉bom头很简单吧
再来一段议论utf8的bom信息的
bom是指php文件本身的存储方式为带bom的utf-8,普通页面的中文乱码方式一般不是由这个原因导致的。
header("content-type: text/html; charset=utf-8");
这句话控制html输出页面的编码方式,
bom只有在windows下采用“记事本”存储为utf-8时才会有,这个可以用winhex把开始的2个字节删掉。
在dreamweaver里面编码设置里面可以设置是否带bom,一般只要php输出的不是图片(gdi stream),bom都不会导致问题。
gdi stream如果开头有了额外的 字符就会显示为 红叉。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!