• 用php把utf8的中的BOM去掉


    今天看到一段不错的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);

     }

     
    ?>


  • 相关阅读:
    Linux基础篇之软件源码包安装
    11-1 网络协议和管理
    bash-2 httpd服务的源码编译安装脚本
    8-1 文本三级剑客之sed
    9-3 磁盘存储与分区
    9-2 yum,dnf和apt
    9-1 软件包管理
    bash-1 初始化CentOS系统的初始化脚本
    3-3 man手册介绍
    5-3 文件权限
  • 原文地址:https://www.cnblogs.com/derrck/p/1701959.html
Copyright © 2020-2023  润新知