Home  >  Article  >  php教程  >  php文件第一行有多余字符,css文件第一行不起作用,bom头在作怪

php文件第一行有多余字符,css文件第一行不起作用,bom头在作怪

WBOY
WBOYOriginal
2016-06-06 19:49:111188browse

window编辑器如果保存为utf8文件就会帮你加上BOM头,以告诉其他编辑器以utf8来显示字符。 在utf-8编码文件中BOM在文件头部,占用三个字节,用来标示该文件属于utf-8编码,现在已经有很多软件识别bom头,但是还有些不能识别bom头,比如PHP就不能识别bom头,这

window编辑器如果保存为utf8文件就会帮你加上BOM头,以告诉其他编辑器以utf8来显示字符。

在utf-8编码文件中BOM在文件头部,占用三个字节,用来标示该文件属于utf-8编码,现在已经有很多软件识别bom头,但是还有些不能识别bom头,比如PHP就不能识别bom头,这也是用记事本编辑utf-8编码后执行就会出错的原因了。

但是在网页上并不需要添加BOM头识别,因为网页上可以使用 head头 指定charset=utf8告诉浏览器用utf8来解释.但是你用window自动的编辑器,编辑,然后有显示在网页上这样就会显示出0xEF 0xBB 0xBF这3个字符。

这样网页上就需要去除0xEF 0xBB 0xBF,可以使用editplus 选择不带BOM的编码,这样就可以去除了。

BOM只有在WINDOWS下采用“记事本”存储为UTF-8时才会有,这个可以用WINHEX把开始的2个字节删掉。
在dreamweaver里面编码设置里面可以设置是否带BOM,一般只要php输出的不是图片(GDI Stream),BOM都不会导致问题。
GDI Stream如果开头有了额外的 字符就会显示为 红叉。

也可以使用php脚本删之。下面贴一段网上的代码:

//此文件用于快速测试UTF8编码的文件是不是加了BOM,并可自动移除
//By Bob Shen

$basedir="."; //修改此行为需要检测的目录,点表示当前目录
$auto=1; //是否自动移除发现的BOM信息。1为是,0为否。

//以下不用改动

if ($dh = opendir($basedir)) {
while (($file = readdir($dh)) !== false) {
if ($file!='.' && $file!='..' && !is_dir($basedir."/".$file)) echo "filename: $file ".checkBOM("$basedir/$file")." <br>";
}
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.</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);
}

不同编码的字节顺序标记的表示

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP学习笔记 2009Next article:PHP 读取文件的几种方法