PHP DOMDocument剥离HTML标记

Bri*_*ger 5 php

我正在研究一个小模板引擎,我正在使用DOMDocument来解析页面.到目前为止,我的测试页面如下所示:

<block name="content">

   <?php echo 'this is some rendered PHP! <br />' ?>

   <p>Main column of <span>content</span></p>

</block>
Run Code Online (Sandbox Code Playgroud)

我班级的一部分看起来像这样:

private function parse($tag, $attr = 'name')
{
    $strict = 0;
    /*** the array to return ***/
    $out = array();
    if($this->totalBlocks() > 0)
    {
        /*** a new dom object ***/
        $dom = new domDocument;
        /*** discard white space ***/
        $dom->preserveWhiteSpace = false;

        /*** load the html into the object ***/
        if($strict==1)
        {
            $dom->loadXML($this->file_contents);
        }
        else
        {
            $dom->loadHTML($this->file_contents);
        }

        /*** the tag by its tag name ***/
        $content = $dom->getElementsByTagname($tag);

        $i = 0;
        foreach ($content as $item)
        {
            /*** add node value to the out array ***/
            $out[$i]['name'] = $item->getAttribute($attr);
            $out[$i]['value'] = $item->nodeValue;
            $i++;
        }
    }

    return $out;
}
Run Code Online (Sandbox Code Playgroud)

我按照我想要的方式工作,它抓取页面上的每个<block>并将其内容注入我的模板,但是,它正在<block>中剥离HTML标记,因此返回以下内容而不是<p>或<span>标签:

this is some rendered PHP! Main column of content
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?:) 谢谢

Dan*_*ian 9

没有:nodeValue是树的值部分的串联,并且永远不会有标签.

我要做的是在$ node下创建树的HTML片段是这样的:


$doc = new DOMDocument();
foreach($node->childNodes as $child) {
    $doc->appendChild($doc->importNode($child, true));
}
return $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)

HTML"片段"实际上比你最初想象的更有问题,因为它们往往缺少像doctypes和字符集这样的东西,这使得很难确定性地在DOM树和HTML片段的部分之间来回传递.