最近遇到一个问题编码问题,有点让人头痛,百度的方法好像不太好用,所以我自己也找了很久,现在总结一个小方法去除utf-8bom的方法,页面总会出现导致页面顶部空白一行,方法如下:
保存为一个php文件,放到网站根目录下,运行可以遍历文件夹并自动清除bom,对文件绝对安全,亲测过的。
<?php ???/* ????* PHP批量去除bom头代码的小工具 ????*/ ???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.</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); ???}
PHP批量去除bom头代码
原文地址:http://www.cnblogs.com/sunny520/p/7798296.html