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
Release: 2025-01-01 10:13:11
Original
327 people have browsed it

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; 
}
Copy after login

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); 
} 
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template