DOM replaceChild does not replace all specified elements

Consider the following code:

$xml = <<<XML <root> <region id='thisRegion'></region> <region id='thatRegion'></region> </root> XML; 

 $partials['thisRegion'] = "<p>Here this region</p>"; $partials['thatRegion'] = "<p>Here 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(); 

Conclusion:

 <root> <p>Here this region</p> <region id="thatRegion"/> </root> 

I canโ€™t understand for my whole life why all the tags in the region are not replaced. This is a problem in my project, and at first I thought it was not a replacement for the elements that I added after loadXML, but with some experiments I could not narrow the template down here.

I would appreciate a code fix to allow me to replace all the tags in the DOMDocument with this Node element. I will also not mind entering a more efficient / practical way to accomplish this if I did not find it.

Thanks in advance!

[edit] PHP 5.3.13

+4
source share
1 answer

NodeLists live. Therefore, when you delete an item inside a document, the NodeList will also be changed. Avoid using a reference to NodeList and start replacing on the last element:

 $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

+7
source

All Articles