问题
Consider the following code:
$xml = <<<XML
<root>
<region id='thisRegion'></region>
<region id='thatRegion'></region>
</root>
XML;
$partials['thisRegion'] = "<p>Here's this region</p>";
$partials['thatRegion'] = "<p>Here's that region</p>";
$DOM = new DOMDocument;
$DOM->loadXML($xml);
$regions = $DOM->getElementsByTagname('region');
foreach( $regions as $region )
{
$id = $region->getAttribute('id');
$partial = $DOM->createDocumentFragment();
$partial->appendXML( $partials[$id] );
$region->parentNode->replaceChild($partial, $region);
}
echo $DOM->saveXML();
The output is:
<root>
<p>Here's this region</p>
<region id="thatRegion"/>
</root>
I cannot for the life of me figure out why all of the region tags aren't being replaced. This is a problem in my project, and at first I thought that it wasn't replacing elements I appended after the loadXML, but with some experimenting I haven't been able to narrow down the pattern here.
I would appreciate a code correction to allow me to replace all tags in a DOMDocument with a given Element Node. I also wouldn't mind any input into a more efficient/practical way to execute this if I haven't found it.
Thanks in advance!
[edit] PHP 5.3.13
回答1:
NodeLists are live. So when you remove an item inside the document, the NodeList also will be modified. Avoid using a reference to the NodeList and start replacing at the last item:
$DOM = new DOMDocument;
$DOM->loadXML($xml);
$regions = $DOM->getElementsByTagname('region');
$regionsCount = $DOM->getElementsByTagName('region')->length;
for($i= $regionsCount;$i>0;--$i)
{
$region=$DOM->getElementsByTagName('region')->item($i-1);
$id = $region->getAttribute('id');
$partial = $DOM->createDocumentFragment();
$partial->appendXML( $partials[$id] );
$region->parentNode->replaceChild($partial, $region);
}
echo $DOM->saveXML();
?>
http://codepad.org/gTjYC4hr
来源:https://stackoverflow.com/questions/11067587/dom-replacechild-not-replacing-all-specified-elements