42

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?

kenorb
  • 155,785
  • 88
  • 678
  • 743
Xaver
  • 11,144
  • 13
  • 56
  • 91
  • If you are trying to get `html_from_node` `class="foo"` you are doing it not correct. There is much easy and short way of doing this. – s.webbandit Oct 16 '12 at 07:47
  • Is this helpful? http://stackoverflow.com/questions/6366351/getting-dom-elements-by-class-name – EricG Oct 16 '12 at 07:48
  • @webbandit I know there is a better way. Please show me! – Xaver Oct 16 '12 at 07:59
  • 3
    Note: This is not duplicate, as it's asking to return html of DOMElement, not DOMDocument as in other question, and these questions have already different answers. – kenorb Feb 21 '15 at 14:55
  • @kenorb hey, it's SO. every question is a duplicate now by definition – c00000fd May 31 '20 at 01:55

2 Answers2

99

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);
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
-11

PHP Simple HTML DOM Parser should do the job!

Saul Martínez
  • 920
  • 13
  • 28