How to get html code of DOMElement node?

Xaver picture Xaver · Oct 16, 2012 · Viewed 33.1k times · Source

I have this html code:

<html>
    <head>
    ...
    </head>
<body>
    <div>
    <div class="foo" data-type="bar">
        SOMECONTENTWITHMORETAGS
    </div>
    </div>
</body>

I already can get the "foo" element (but only its content) with this function:

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

But I'd like to return all html tags (including its attributes) of DOMElement. How I can do that?

Answer

lonesomeday picture lonesomeday · Oct 16, 2012

Use the optional argument to DOMDocument::saveHTML: this says "output this element only".

return $node->ownerDocument->saveHTML($node);

Note that the argument is only available from PHP 5.3.6. Before that, you need to use DOMDocument::saveXML instead. The results may be slightly different. Also, if you already have a reference to the document, you can just do this:

$doc->saveHTML($node);