How to Access DOM Element InnerHTML in PHP DOM API
In the PHP DOM implementation, accessing the innerHTML of a DOMNode requires a specific approach. Here's a reliable solution and how it compares to other options.
The PHP DOM API does not provide a dedicated function to retrieve the innerHTML. Unlike in JavaScript, where innerHTML is a property of an element, in PHP DOM, you need to manually iterate over the node's children to build the innerHTML.
Updated Variant with PHP Manual User Note #89718
The user note suggests an updated variant for constructing the innerHTML:
function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; }
Example Usage
Assuming you have an HTML string stored in $html_string, here's how you can implement this function:
$dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load($html_string); $domTables = $dom->getElementsByTagName("table"); foreach ($domTables as $table) { echo DOMinnerHTML($table); }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3