PHPverse 2025

Voting

The Note You're Voting On

Drupella
13 years ago
Here is a fast innerHTML function that returns the result without iterating over child nodes.

<?php
function innerHTML($el) {
$doc = new DOMDocument();
$doc->appendChild($doc->importNode($el, TRUE));
$html = trim($doc->saveHTML());
$tag = $el->nodeName;
return
preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
?>

Example
<?php
$doc
= new DOMDocument();
// A corrupt HTML string
$doc->loadHTML('<HTML><A HREF="ss">asd</A>');
$body = $doc->getElementsByTagName('body')->item(0);
print
htmlspecialchars(innerHTML($body));
// Prints <a href="ss">asd</a>
?>

<< Back to user notes page

To Top