Sometimes, we want to get innerHTML of DOMNode with PHP.
In this article, we’ll look at how to get innerHTML of DOMNode with PHP.
How to get innerHTML of DOMNode with PHP?
To get innerHTML of DOMNode with PHP, we can call saveHTML
.
For instance, we write
<?php
function DOMinnerHTML(DOMNode $element)
{
$innerHTML = "";
$children = $element->childNodes;
foreach ($children as $child)
{
$innerHTML .= $element->ownerDocument->saveHTML($child);
}
return $innerHTML;
}
$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);
}
to create the DOMinnerHTML
function that loops through the $childrenm
elements and get the inner HTML of each $child
element with $element->ownerDocument->saveHTML
.
We concatenate the returned HTML to the $innerHTML
string and return it once the loop is done.
Then we create a new DOMDocument
object.
We call load
to parse the $html_string
into contents of the DOMDocument
object.
And then we call getElementsByTagName
to get the table element.
Then we use a foreach loop that calls DOMinnerHTML
to get the inner HTML of each $table
returned and echo the values.
Conclusion
To get innerHTML of DOMNode with PHP, we can call saveHTML
.