How to get innerHTML of DOMNode?

Dawid Ohia picture Dawid Ohia · Jan 18, 2010 · Viewed 92.2k times · Source

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.

Answer

Haim Evgi picture Haim Evgi · Jan 18, 2010

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); 
} 
?>