hi,欢迎访问本站!
当前位置: 首页编程开发正文

php如何去除BOM头

墨初 编程开发 388阅读

在utf-8编码文件中BOM会存在于文件头部,占用三个字节,用来表示该文件属于utf-8编码。虽然现在有不少的软件已经可以识别到bom头,但还有一些不能识别bom头的软件或编程语言,php就属于不能识别bom头的编程语言。这也是很多phper用一些偏门的编辑器写php代码经常出错的原因之一了。

UTF-8 的BOM对UTF-8没有任何作用,主要是为了支援UTF-16,UTF-32才加上的BOM。BOM签名的意思就是告诉编辑器当前文件采用哪种编码,方便编辑器进行识别,但是BOM虽然在编辑器中不显示,但也是会产生输出,多出一个空行。

既然bom头的用法不大,我们可以使用php将bom头删除掉。

php 删除BOM头的方法

例:

/**
 * @name 删除内容中的BOM头
 * @param string $contents 需要过滤bom头的内容
 * 
 * @return string 返回没有bom头的内容
 * @host https://www.73so.com
 */
function del_bom($contents)
{
    $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);
        return $rest;
    }else{
        return $contents;
    }
}

# 读取文件中的内容
$cont = file_get_contents('text.txt'); 
echo del_bom($cont);

php 批量删除文件中的 BOM 头

如果大量的文件存在于bom头,可以使用下面的方法批量处理文件中的bom头。

例:

#73so.com
$auto = true; //定义是否去掉文件中的BOM头,如果为 false 则只检测是否含有 BOM 头
$basedir = ''; //需要批量处理文件的上传目录
checkdir($basedir);//检测目录
function checkdir($basedir)
{
    if ($dh = opendir($basedir)) {
        while (($file = readdir($dh)) !== false) {
            if($file{0} == '.'){
                continue;
            }
            if($file != '.' && $file != '..'){
                if (!is_dir($basedir."/".$file)) {
                    echo "filename: $basedir/$file ".checkBOM("$basedir/$file")." <br>";
                }else{
                    $dirname = $basedir."/".$file;
                    checkdir($dirname);
                }
            }
        }
        closedir($dh);
    }
}
//检查文件是否有BOM头,通过 全局变量 $auto 来控制是否删除文件中的BOM头
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) {
            $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.");
    }    
}

//重写文件,以达到删除BOM头的目的
function rewrite ($filename, $data) 
{
    $filenum = fopen($filename, "w");
    flock($filenum, LOCK_EX);
    fwrite($filenum, $data);
    fclose($filenum);
}

ps:将上面的代码保存为php文件,然后直接调用即可!

标签:
声明:无特别说明,转载请标明本文来源!
相关推荐