美文网首页
PHP检测并清除文件开头的BOM头

PHP检测并清除文件开头的BOM头

作者: VincentH | 来源:发表于2017-07-04 10:14 被阅读0次

代码直接记事本打开经常会自动变成含有bom头格式的文本,当我们知道某个文件含有bom头的时候我们经常是使用notapad++的encoding -> convert to utf8 让他删除bom头,但是当我们不知道究竟是项目里哪个文件有bom头的时候,显然此方法不管用,于是我们可以使用以下的代码让他自动检测并且清除bom头

<?php  
/*检测并清除BOM*/  
$basedir = dirname(__FILE__);//扫描当前文件路径 可自动设置  
$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);  
                }  
            }  
        }//end while  
    closedir($dh);  
    }//end if($dh  
}//end function  
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.");  
}//end function  
function rewrite($filename, $data){  
    $filenum = fopen($filename, "w");  
    flock($filenum, LOCK_EX);  
    fwrite($filenum, $data);  
    fclose($filenum);  
}

相关文章

网友评论

      本文标题:PHP检测并清除文件开头的BOM头

      本文链接:https://www.haomeiwen.com/subject/uvpthxtx.html