zoukankan      html  css  js  c++  java
  • PHP批量去除bom头代码

      最近遇到一个问题编码问题,有点让人头痛,百度的方法好像不太好用,所以我自己也找了很久,现在总结一个小方法去除utf-8bom的方法,页面总会出现&#65279导致页面顶部空白一行,方法如下:

      保存为一个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);
        }
    
  • 相关阅读:
    99%的人都理解错了HTTP中GET与POST的区别
    idea 使用
    一道java算法题
    记一次jedis并发使用问题JedisException: Could not return the resource to the pool
    我珍藏的神兵利器
    记一次诡异的debug
    spring cloud config
    spring mvc 集成quartz
    git使用下
    Mongo--03 mongo副本集、备份与恢复
  • 原文地址:https://www.cnblogs.com/sunny520/p/7798296.html
Copyright © 2011-2022 走看看