What's the simplest way to get the innerHTML (tags and all) of a DOMElement using PHP's DOM functions?
Asked
Active
Viewed 1.1k times
2 Answers
10
$html = '';
foreach($parentElement->childNodes as $node) {
$html .= $dom->saveHTML($node);
}

alex
- 479,566
- 201
- 878
- 984
-
This doesn't work if the childNodes have childNodes though – Ben G Aug 23 '11 at 05:34
-
@babonk That's not true. Look at the bottom of the CodePad. – alex Aug 23 '11 at 05:47
-
Weird, I got an error locally when I used it.. might be a version thing – Ben G Aug 23 '11 at 06:07
-
3@babonk `saveHTML()` with a node is only supported >= 5.3.6. You may need to use `saveXML()` if using a prior version. – alex Aug 23 '11 at 06:19
3
Inner HTML
Try approach suggested by @trincot:
$html = implode(array_map([$node->ownerDocument,"saveHTML"], iterator_to_array($node->childNodes)));
Outer HTML
Try:
$html = $node->ownerDocument->saveHTML($node);
or in PHP lower than 5.3.6:
$html = $node->ownerDocument->saveXML($node);