今天心血来潮,想写一个php创建utf-8文件的功能,各种百度谷歌后,发现创建的utf-8文件有bom,那么我就想写一个没有bom头的php创建utf-8文件功能,经过自己的各种尝试和实践后,终于让我搞定了。要知道文件本身的格式,也是影响页面乱码的重要原因,详细可以看我的博文:你的页面为什么乱码了!,bom呢会让页面头部多一行空白,所以也要去掉。
这个功能分两步完成,文件本身编码的格式就是取决于bom头,所以我们要用php写入一个utf-8指定的bom头,并且因为一些特殊的原因,我们不能中途用编辑器打开这个创建的带bom的文件,因为很多编辑器有自己的过滤功能,会自动讲文件另存为utf-8后会因为内容中全是英文而自动转为ANSI,原因就是因为中文才有编码问题,而英文和数字没有。所以我们首先创建一个文件,写入utf-8的bom头,并写入utf-8编码的中文字符(为什么一定要中文字符呢,这就是为什么有的时候我们发现我们无论怎么另存一个文件都无法另存为utf-8的,而内容中如果有中文,就可以了,只有中文才有utf-8!!!),这时候就会创建一个带有bom的utf-8文件,但是中文字符会显示为空白,原因这个文件是先写入内容,后转化格式的。然后,我们再用php将这个bom头截取掉就变成了没有bom的utf-8文件。所以,一般如果你要创建这样的文件,要先这样来创建,然后再用php打开写入你想要写入的内容。代码入下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php $filename = 'test.html'; $f=fopen($filename, "wb"); $text=utf8_encode('我a'); //必须是中文 //先用函数utf8_encode将所需写入的数据变成UTF编码格式。 $text="\xEF\xBB\xBF".$text; //"\xEF\xBB\xBF",这串字符不可缺少,生成的文件将成为UTF-8格式,否则依然是ANSI格式。 fputs($f, $text); //写入。 fclose($f); echo checkBOM($filename); function checkBOM ($filename) { $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) { $rest = substr($contents, 3); rewrite ($filename, $rest); return ("<font color=red>ok</font>"); } else return ("BOM Not Found."); } function rewrite ($filename, $data) { $filenum = fopen($filename, "w"); flock($filenum, LOCK_EX); fwrite($filenum, $data); fclose($filenum); } ?> |
下面附上一个直接批量去除目录下所有文件bom的php功能代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php if (isset($_GET['dir'])){ //config the basedir $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.</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); } ?> |
程序本天成,妙手偶得之!我们只是代码的搬运工!
转载请注明:http://www.521php.com/archives/1101/
2013年03月07日 下午 11:04 Json | 引用 | #1
呵呵,写得挺好的。