Search code examples
phpdominnerhtml

How to get innerHTML of DOMNode?


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.


Solution

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