您的位置:首页 > 编程语言 > PHP开发

用php把utf8的中的BOM去掉

2010-04-01 09:19 435 查看
今天看到一段不错的php程序,可以自动把你所有的文件的BOM去掉,而这全部过程只需要上传并运行一下,非常不错,保留下来方便下次使用。

代码

Write UTF-8 BOM=0

Write UTF-8 BOM NF=0

这段php程序如下,保存成php文件放在根目录中执行一次就行了,会自动去除文件头中的BOM。

<?php

//remove the utf-8 boms

//by magicbug at gmail dot com

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);

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: