PHP DOMDocument剥离HTML标记

时间:2020-03-05 18:59:27  来源:igfitidea点击:

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

<block name="content">

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

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

</block>

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

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;
}

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

this is some rendered PHP! Main column of content

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

解决方案

回答

Nothing:nodeValue是树的value部分的串联,并且永远不会有标签。

我要在$ node下制作树的HTML片段的操作是这样的:

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

HTML"片段"实际上比我们一开始想的要麻烦得多,因为它们往往缺少诸如doctype和字符集之类的东西,这使得很难确定性地在DOM树的各个部分和HTML片段之间来回移动。