Viewed   785 times

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.

 Answers

3

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); 
} 
?> 
Wednesday, August 31, 2022
1

You're affected by one of PHP bugs. The issue was present only in PHP 5.6.8 and 5.6.9. Most likely you have affected PHP version on the server, and bug-free version on your localhost.

The bug itself forbids all null characters in HTML document you're loading, so as a workaround you may try to remove those (actually not needed) characters before further parsing.

$document = new DOMDocument();
$p_result_without_null_chars = str_replace("", '', $p_result)
$document->loadHTML($p_result_without_null_chars);
Saturday, December 3, 2022
4

15 seconds to create and json_encode 10K elements .. this can't be right. The bottle neck is undoubtedly not PHP here. Where is that data coming from, a database ? In a single query or embedded queries in a loop ? Can the data be cached ? If so, do so.

You need to properly benchmark before optimizing, what you're trying to do now is trim milliseconds off an operation that takes 15 seconds.

Friday, August 12, 2022
 
mao
 
mao
5
<element onClick="alert(this.innerHTML);"> ... </element>
Thursday, September 15, 2022
 
5
$('.a')[0].innerHTML;
$('.a')[1].innerHTML;

FIDDLE

Tuesday, August 30, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :