如何获取DOMElement节点的HTML代码?

Xav*_*ver 28 php dom domdocument dom-node

我有这个HTML代码:

<html>
    <head>
    ...
    </head>
<body>
    <div>
    <div class="foo" data-type="bar">
        SOMECONTENTWITHMORETAGS
    </div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

我已经可以使用此函数获取"foo"元素(但仅包含其内容):

private function get_html_from_node($node){
  $html = '';
  $children = $node->childNodes;

  foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $html .= $tmp_doc->saveHTML();
  } 
  return $html;
}
Run Code Online (Sandbox Code Playgroud)

但我想返回DOMElement的所有html标签(包括其属性).我怎么能这样做?

lon*_*day 64

使用可选参数DOMDocument::saveHTML:this表示"仅输出此元素".

return $node->ownerDocument->saveHTML($node);
Run Code Online (Sandbox Code Playgroud)

请注意,该参数仅适用于PHP 5.3.6.在此之前,您需要使用DOMDocument::saveXML.结果可能略有不同.此外,如果您已经有对该文档的引用,您可以这样做:

$doc->saveHTML($node);
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是我需要的,但它适用于应与 3.4 版一起使用的 WordPress 插件,而此版本需要 php 5.2.4。 (2认同)
  • 我无法发布完整的代码作为答案,但这个答案是不正确的。这是工作代码:https://gist.github.com/komlenic/1374083 (2认同)