关于php:DOMDocument :: loadHTML错误

DOMDocument::loadHTML error

我构建了一个脚本,该脚本将页面上的所有CSS组合在一起,以在我的cms中使用它。 很长一段时间以来,它都工作正常,我出现了此错误:


Warning: DOMDocument::loadHTML()
[domdocument.loadhtml]: Tag header invalid in Entity, line: 10 in
css.php on line 26

Warning:
DOMDocument::loadHTML() [domdocument.loadhtml]: Tag nav invalid in
Entity, line: 10 in css.php on line 26

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Tag
section invalid in Entity, line: 22 in css.php on line
26

This is the php script

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
header('Content-type: text/css');
include ('../global.php');

if ($usetpl == '1') {
    $client = New client();
    $tplname = $client->template();
    $location ="../templates/$tplname/header.php";
    $page = file_get_contents($location);
} else {
    $page = file_get_contents('../index.php');
}

class StyleSheets extends DOMDocument implements IteratorAggregate
{

    public function __construct ($source)
    {
        parent::__construct();
        $this->loadHTML($source);
    }

    public function getIterator ()
    {
        static $array;
        if (NULL === $array) {
            $xp = new DOMXPath($this);
            $expression = '//head/link[@rel="stylesheet"]/@href';
            $array = array();
            foreach ($xp->query($expression) as $node)
                $array[] = $node->nodeValue;
        }
        return new ArrayIterator($array);
    }
}

foreach (new StyleSheets($page) as $index => $file) {
    $css = file_get_contents($file);
    echo $css;
}


Header,Nav和Section是HTML5中的元素。 因为HTML5开发人员觉得记住公共和系统标识符太难了,所以DocType声明只是:

1
<!DOCTYPE html>

换句话说,没有要检查的DTD,这将使DOM使用HTML4过渡DTD,并且不包含那些元素,因此出现警告。

要取消警告,请放

在调用loadHTML之前和

之后。

一种替代方法是使用https://github.com/html5lib/html5lib-php。


使用DOMDocument对象,应该可以在加载方法之前放置@,以便禁止所有警告。

1
2
$dom = new DOMDocument;
@$dom->loadHTML($source);

并继续。