PHP removeChild仅删除3个元素中的2个[重复]

This question already has an answer here:

I'm new to PHP so let me apologize in advance. I have been working at parsing an XML, I have pretty much everything working thanks to articles here but I am seeing some odd behavior when deleting elements from my XML.

I have pulled an XML from a web service and it is working great, now I need to delete every instance of an element, XPath has proved to be a challenge (for me) so now I have this:

$idlist = $dom2->getElementsByTagName('ELEMENTID');
foreach ($idlist as $id) {
    print "<!--"."Removing Node ".$id->nodeName."=".$id->nodeValue."-->";
    //$id->parentNode->removeChild($id);
    }

The reason my print is as an XML comment is that I am generating an XML output file.

Now, my XML contains three elements that match i.e. 123 - when I have the code as shown it prints out the nodeName and nodeValue of all three. However, if I uncomment the removeChild line things get weird, it deletes the first and third matching elements but not the second one.

Hopefully my explanation is somewhat clear, is there something about removeChild() that might cause it to react in this way?

Thanks, Chris.

</div>

As seems to happen often just after I give up and post I come across a solution, it seems there's a peculiarity when removing nodes that it skips some UNLESS you go backwards.

If I use a for loop and go backwards through the array all is well.

$idlist = $dom2->getElementsByTagName('ELEMENTID');
$length = $idlist->length;
for ($i=$length-1;$i>=0;$i--)
{
    $id = $idlist->item($i);
    $id->parentNode->removeChild($id);
}