PHP页面头部输出空白行部分原因

来源:互联网 发布:sqlserver备注查询 编辑:程序博客网 时间:2024/05/21 07:01

   转自安静PHP技术博客

作为Php-coder经常会遇到的莫过于浏览器样式错乱问题,当然这不是指csshack问题,在chrome下正常而在Ie类内核浏览器上显示不正常.

很多时候你会在查看网页源码时看到距离上面会有一行换行,可查看所有加载过的Php代码并没有相关的换行空白符,通过复制源码用2进制文件打开后头部会有EFBBBF内容,恩,很不幸的告诉你你使用的编辑器自动给你的文件加了utf-8 BOM

当然上述得只是一种情况,还有一些比如在头部PHP,session_start()前有输出,服务器关闭了报错也会出现空白行。

一般来说头部空白会有三种原因导致:

  • PHP文件中有utf8BOM头,一般是因为编辑器特别是DW,或者notepad导致的.推荐使用UE,Editplus,sublime等。
  • PHP文件结尾?>后面有空白换行.推荐一般情况下会被包含的.php结尾一般都不加?>。
  • session_start()头部输出前有错误.报错打开查看错误。

何谓BOM?

“EF BB BF” 这三个字节就叫BOM,BOM的全称叫做”Byte Order Mard”.在utf-8文件中常用BOM来表明这个文件是UTF-8文件,而BOM的本意实在utf16中用来表示高低字节序列的。在字节流之前有BOM表示采用低字节序列(低字节在前面),而utf8不用考虑字节序列,所以其实有无BOM都可以。UTF-8以字节为编码单元,没有字节序的问题。UTF-16以两个字节为编码单元,在解释一个UTF-16文本前,首先要弄清楚每个编码单元的字节序。例如收到一个“奎”的Unicode编码是594E,“乙”的Unicode编码是4E59。如果我们收到UTF-16字节流“594E”,那么这是 “奎”还是“乙”?

最后提供一个utf8bom头部PHP类

<?phpif (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")." \n\r";             }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);  }

参考

  1. 关于字符串描述 http://en.wikipedia.org/wiki/Byte_order_mark
  2. 知乎关于UTF8与UTF8BOM区别 http://www.zhihu.com/question/20167122
  3. http://www.cnblogs.com/zhongru_tu/archive/2008/04/11/1147792.html

0 0
原创粉丝点击