What function do you use to get innerHTML of a given DOMNode in the PHP DOM implementation? Can someone give reliable solution?
Of course outerHTML will do too.
php function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML . = $element->ownerDocument->saveHTML($child); } return $innerHTML; } ?>
How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.
The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.
For that reason, it is recommended that instead of innerHTML you use: Element.SetHTML() to sanitize the text before it is inserted into the DOM.
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; } ?>
Example:
<?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); } ?>
Here is a version in a functional programming style:
function innerHTML($node) { return implode(array_map([$node->ownerDocument,"saveHTML"], iterator_to_array($node->childNodes))); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With