【问题标题】:PHP DOMDocument stripping HTML tagsPHP DOMDocument 剥离 HTML 标签
【发布时间】:2017-04-12 02:07:53
【问题描述】:

我正在开发一个小型模板引擎,并且正在使用 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;
}

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

标签:

this is some rendered PHP! Main column of content

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

【问题讨论】:

    标签: php


    【解决方案1】:

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

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

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

    HTML“片段”实际上比你一开始想象的更成问题,因为它们往往缺少诸如文档类型和字符集之类的东西,这使得很难确定地在 DOM 树的部分和 HTML 片段之间来回切换.

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2015-02-02
      • 1970-01-01
      • 2011-12-13
      • 2011-09-11
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      相关资源
      最近更新 更多