Home >Backend Development >PHP Tutorial >How Can I Get the Inner HTML of a DOM Node in PHP?

How Can I Get the Inner HTML of a DOM Node in PHP?

Susan Sarandon
Susan SarandonOriginal
2025-01-01 10:13:11313browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn