Reputation: 2974
I'm loading up an HTML fragment into a DOMDocument, modifying it, and then converting back to a string.
The closest I can get is this...
$html_string = "<b>my html fragment</b><div>more child nodes</div>";
$doc_html = new DOMDocument();
$doc_html->loadHTML( $html_string );
//do stuff
$html_string = $doc_html->saveHTML( $doc_html->getElementsByTagName('body')->item(0) );
The problem here is that loadHTML wraps it in a <html>
and <body>
tag. So I use getElementsByTagName to stringify just the body node, but it includes the body node it's self...
<body><b>my html fragment</b><div>more child nodes</div></body>
But i just want the child nodes like the input string.
Other than looping all children and concatenating a string / running a req ex on the resulting string, is there a simple way to do this?
m
Upvotes: 0
Views: 1071
Reputation: 96189
<?php
$doc = doc();
$xp = new DOMXpath($doc);
$nl = $xp->query('//a');
foreach($nl as $n) {
$df = $doc->createDocumentFragment();
$nodes = array();
foreach( $n->childNodes as $cn ) {
$nodes[] = $cn;
}
foreach($nodes as $cn) {
$df->appendChild( $cn );
}
echo $doc->savexml( $df );
}
function doc() {
$doc = new DOMDocument;
$doc->loadxml(<<< eox
<doc>
<a>
<b>1</b>
<b>2</b>
<b>3</b>
<b>4</b>
</a>
</doc>
eox
);
return $doc;
}
prints
<b>1</b>
<b>2</b>
<b>3</b>
<b>4</b>
see http://docs.php.net/domdocumentfragment
Upvotes: 1