UTF-8文件的BOM头的来由及去除方法

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

 

2. 包含BOM头文件的产生

    在windows环境下,用记事本打开任何一个文本文件,另存为utf-8格式后,这样文件就自动被加上了BOM头信息。

    比较:

            utf-8(含BOM头)

            

            utf-8(不含BOM头)

            

    

    从上图的比较中,可以很明显的看出,含BOM头的文件多出三个字节 efbbbf。

 

3. BOM头信息的去除方法

    用Notepad++打开文件,选择 格式 -> 以UTF-8无BOM格式编码,再保存就行。如下图:

 

4. 在PHP类的项目中,自动处理BOM头信息(只需要将此文件放在项目根目录下,从浏览器访问即可)

<</font>?php if (isset($_GET['dir'])) { //设置文件目录 $basedir = $_GET['dir']; } else { $basedir = '.'; } 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") . " "; } else { $dirname = $basedir . "/" . $file; checkdir($dirname); } } } closedir($dh); } } function checkBOM($filename, $auto = 1) { $contents = file_get_contents($filename); $charset[1] = substr($contents, 0, 1); $charset[2] = substr($contents, 1, 1); $charset[3] = substr($contents, 2, 1);  

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/5e10e9b35923e64de431c8dde07a81d2.html