>  기사  >  php教程  >  Php引用文件引起的空白行问题(UTF-8)

Php引用文件引起的空白行问题(UTF-8)

WBOY
WBOY원래의
2016-05-25 16:52:121062검색

引用文件指的是include、require_once引用其它文件引起的空白行,这其实是你用记事本编辑UTF-8文件以后,虽然你还是保存为UTF-8格式,但系统会自动给文件加两个bom标记,但是ie只能忽略一个,另一个就是空白行了。

解决办法就是:不要用记事本去编辑UTF-8文件,要用其它工具,比Dreamw、EmEditor 、Visual Studio 2008等编辑工具编辑UTF-8文件后保存。

我的两个站用记事本编辑后顶部就有空白行,起初以为是css设置问题,结果是bom标记引起的。

还有一种办法,如果你是大量文件都这样我们可使用一个php函数来搞定,把以下代码复制到一个PHP文件里面,然后放在需要清除BOM头的目录一下运行,就可以批量把PHP空白的首行清除掉,太给力了,代码如下:

<?php
if (isset($_GET[&#39;dir&#39;])) { //设置文件目录
    $basedir = $_GET[&#39;dir&#39;];
} else {
    $basedir = &#39;.&#39;;
}
$auto = 1;
checkdir($basedir);
function checkdir($basedir) {
    if ($dh = opendir($basedir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != &#39;.&#39; && $file != &#39;..&#39;) {
                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);
}
?>


永久链接:

转载随意!带上文章地址吧。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.