Home >Backend Development >PHP Tutorial >How Can I Get the Inner HTML of a DOM Node in PHP?
Retrieving the Inner HTML of DOM Nodes in PHP
To obtain the inner HTML of a DOM node in PHP, leverage the DOMinnerHTML() function. This function traverses the child nodes of the given DOM node and appends their HTML representation to a string.
Implementation:
function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; }
Example:
$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); }
Note: To retrieve the outer HTML, use $element->ownerDocument->saveHTML($element) instead of DOMinnerHTML($element).
The above is the detailed content of How Can I Get the Inner HTML of a DOM Node in PHP?. For more information, please follow other related articles on the PHP Chinese website!