Home >Backend Development >PHP Tutorial >How Can I Extract Inner HTML from DOM Nodes in PHP?

How Can I Extract Inner HTML from DOM Nodes in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 13:56:11887browse

How Can I Extract Inner HTML from DOM Nodes in PHP?

Extracting Inner HTML from DOM Nodes in PHP

The PHP DOM implementation does not natively provide a method for retrieving the innerHTML of a given DOMNode. To address this, developers have devised a workaround using the DOMinnerHTML() function.

DOMinnerHTML Function

The DOMinnerHTML() function takes a DOMNode as its parameter and returns the innerHTML as a string. It recursively iterates through the child nodes of the DOMNode, building the innerHTML by serializing each child node using $element->ownerDocument->saveHTML($child).

function DOMinnerHTML(DOMNode $element) 
{ 
    $innerHTML = ""; 
    $children  = $element->childNodes;

    foreach ($children as $child) 
    { 
        $innerHTML .= $element->ownerDocument->saveHTML($child);
    }

    return $innerHTML; 
} 

Example Usage

To use the DOMinnerHTML() function, create a new DOMDocument object, load your HTML into it, and retrieve the DOMNodeList containing your desired nodes. Then, iterate through the DOMNodeList and call DOMinnerHTML() on each node to extract its 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); 
} 

This workaround provides a reliable solution for retrieving the innerHTML of DOMNodes in PHP, enabling developers to access and modify the content of DOM elements without using external libraries.

The above is the detailed content of How Can I Extract Inner HTML from DOM Nodes 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