PHP如何去除BOM-PHP问题

资源魔 29 0

PHP去除了BOM的办法:起首创立一个PHP代码文件;而后设置文件目次;接着界说一个“checkdir”和“checkBOM”办法;最初将此代码文件放到根目次下并运转便可。

/* 
 +------------------------------------------------------------------------------------------- 
 + Title        : 去掉BOM头办法 
 + Author       : hello_sgw 
 + Version      : V1.0.0.1 
 + Initial-Time : 2017-08-12 15:18
 + Last-time    : 2017-08-12 16:01
 + Desc         : 
 +------------------------------------------------------------------------------------------- 
*/

本人正在挪用接口时分,由于用到了对方提供的封装办法,正在输入一组数据时分不断显示谬误,最初想到可能对方给的办法外面含有编码成绩(具备BOM头),以是上彀搜寻到一个检测BOM的办法而且能够去除了从新天生新文件,运用之后就能失常显示数据了。

甚么是BOM头?

BOM --Byte Order Mark,中文名译作“字节程序标志”,正在utf-8编码文件中BOM正在文件头部,占用三个字节,用来标示该文件属于utf-8编码,
如今曾经有不少软件辨认bom头,然而另有些不克不及辨认bom头,比方PHP就不克不及辨认bom头,这也是用记事本编纂utf-8编码后执行就会犯错的缘由了。

处理办法:

# 这里代码为PHP形式去除了以后目次及字目次一切文件BOM信息,只需将此代码文件放到根目次下,而后阅读器运转拜访就能够了

<?php
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);
}

不少相干常识,请拜访PHP中文网!

以上就是PHP若何去除了BOM的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 php故障解决 php使用问题 bom

抱歉,评论功能暂时关闭!