How to get innerHTML of DOMNode?

✔ Recommended Answer

Compare this updated variant with PHP Manual User Note #89718:

<?php function DOMinnerHTML(DOMNode $element) {     $innerHTML = "";     $children  = $element->childNodes;    foreach ($children as $child)     {         $innerHTML .= $element->ownerDocument->saveHTML($child);    }    return $innerHTML; } ?> 


<?php $dom= new DOMDocument(); $dom->preserveWhiteSpace = false;$dom->formatOutput       = true;$dom->load($html_string); $domTables = $dom->getElementsByTagName("table"); // Iterate over DOMNodeList (Implements Traversable)foreach ($domTables as $table) {     echo DOMinnerHTML($table); } ?> 


Answered By: Haim Evgi

Method #2

To get the innerHTML of a DOMNode in PHP, you can use the DOMDocument and DOMXPath classes to load and query the HTML document.

Here is an example code snippet to get the innerHTML of a DOMNode:

// Load the HTML document $doc = new DOMDocument(); $doc->loadHTML('<html><body><div>Hello world!</div></body></html>'); // Create an XPath query to select the div element $xpath = new DOMXPath($doc); $divs = $xpath->query('//div'); // Get the innerHTML of the first div element if ($divs->length > 0) { $div = $divs->item(0); $innerHTML = ''; foreach ($div->childNodes as $child) { $innerHTML .= $doc->saveHTML($child); } echo $innerHTML; // Output: Hello world! }

In this example, we first load the HTML document using the DOMDocument class. Then, we create an XPath query to select the div element using the DOMXPath class. We then get the first div element from the query result, and iterate over its child nodes to concatenate their HTML using the saveHTML() method of the DOMDocument class. Finally, we output the innerHTML of the div element.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755