Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html code of DOMElement node? [duplicate]

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?

like image 800
Xaver Avatar asked Oct 16 '12 07:10

Xaver


People also ask

How do you clone a node in HTML?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).

Can you clone from a node?

cloneNode() The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not. Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners.

Does node cloneNode () clone the node's event listeners?

cloneNode() does not copy event listeners. In fact, there's no way of getting hold of event listeners via the DOM once they've been attached, so your options are: Add all the event listeners manually to your cloned node.


1 Answers

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);
like image 199
lonesomeday Avatar answered Oct 18 '22 23:10

lonesomeday