php 去除文件BOM头的方法

180it 2021-05-18 PM 1996℃ 0条

文件BOM头的介绍
在 utf-8 编码的文件头部会含有一个BOM头,它占用三个字节,是用来标示该文件属于utf-8编码。

现在已经有很多软件都可以识别bom头的,但还是有一些软件或编程语言是识别不了BOM头的,而php就属于不能识别BOM头的编程语言。

php 删除内容中的BOM头
一般含有BOM头的内容都是从 utf-8 编码的文本文件中提取的,我们可以通过php对内容进行处理,来达到去掉 BOM 头的目的。

php代码:

<?php
//定义一个删除BOM头的PHP函数
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;
    }
}
?>

函数的调用:

<?php
//从 TXT 文件读取内容
$cont = file_get_contents('text.txt'); 
// 删除内容中的 BOM 头
echo del_bom($cont);
?>

php 批量删除文件中的 BOM 头
在使用记事本或一些其它别的编程软件编写PHP文件时,如果操作不规范很有可能会留有BOM头,如果是单个文件的情况下直接在编程软件中修改下即可,如果文件多了,就要使用批量的处理方法。下面就来说一个php批量去除文件中bom头的方法。

php代码:

<?php
if (isset($_GET['dir'])) { //设置文件目录 
    $basedir = $_GET['dir']; 
    }else{ 
    $basedir = '.'; 
} 
$auto = true; //定义是否去掉文件中的BOM头,如果为 false 则只检测是否含有 BOM 头
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);
}
?>


支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 去除文件BOM头的方法