DOM replaceChild not replacing all specified elements

删除回忆录丶 提交于 2020-01-14 09:06:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!