Home >Backend Development >PHP Tutorial >How to Get the innerHTML of DOMNodes Using PHP's DOM Implementation?
Getting innerHTML of DOMNodes in PHP DOM Implementation
When working with PHP's DOM implementation, it's essential to understand the methods available for retrieving the innerHTML of DOMNodes. The following exploration will provide a comprehensive solution to this common task.
PHP Implementation:
To acquire the innerHTML of a given DOMNode, PHP offers two primary functions:
The PHP Manual User Note #89718 provides an updated version of this custom function:
function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; }
This function recursively traverses the DOMNode's children, utilizing saveHTML() to retrieve the HTML representation of each child.
This method returns the HTML representation of the specified DOMNode. It can be used on the ownerDocument of the DOMNode to obtain its innerHTML.
Usage Example:
Here's an example demonstrating the usage of DOMinnerHTML() function:
$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); }
This script retrieves all tables from an HTML string and prints their innerHTML using the DOMinnerHTML() function.
The above is the detailed content of How to Get the innerHTML of DOMNodes Using PHP's DOM Implementation?. For more information, please follow other related articles on the PHP Chinese website!