Edit report at https://bugs.php.net/bug.php?id=52369&edit=1
ID: 52369 Comment by: gmblar+php at gmail dot com Reported by: giorgio dot liscio at email dot it Summary: trying to delete nodes while looping domnodelist do not delete them Status: Open Type: Bug Package: DOM XML related Operating System: all PHP Version: 5.3.2 Block user comment: N Private report: N New Comment: Create a document <?php $document = new DOMDocument(); $document->formatOutput = true; $root = $document->appendChild($document->createElement('root')); for($i = 0; $i < 10; $i++) { $root->appendChild($document->createElement('child', $i)); } echo $document->saveXML(); ?> Result: <?xml version="1.0"?> <root> <child>0</child> <child>1</child> <child>2</child> <child>3</child> <child>4</child> <child>5</child> <child>6</child> <child>7</child> <child>8</child> <child>9</child> </root> When you alter elements in the DOMNodeList in a foreach loop, it may produce unexpected results <?php foreach($document->getElementsByTagName('child') as $element) { $root->removeChild($element); } echo $document->saveXML(); ?> Result: <?xml version="1.0"?> <root> <child>1</child> <child>3</child> <child>5</child> <child>7</child> <child>9</child> </root> First copy the elements from the DOMNodeList to an array with iterator_to_array <?php foreach(iterator_to_array($document->getElementsByTagName('child')) as $element) { $root->removeChild($element); } ?> Result: <?xml version="1.0"?> <root/> Previous Comments: ------------------------------------------------------------------------ [2010-07-20 01:11:39] giorgio dot liscio at email dot it not a bug? ------------------------------------------------------------------------ [2010-07-18 13:14:54] giorgio dot liscio at email dot it Description: ------------ hi, as summary says here is the test code <?php $s = '<div><abc /><abc /><abc /><abc /></div>'; $a = new DOMDocument(); $a->loadXML($s); $els = $a->getElementsByTagName("abc"); // uncomment those three lines to fix //foreach($els as $b) // $els2[]=$b; //$els=$els2; foreach($els as $el) $el->parentNode->removeChild($el); echo "<textarea rows=20 cols=50>"; echo "document element (<div>) should be empty:\n"; echo $a->saveXML(); ?> uncomment lines to see the expected behavior ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=52369&edit=1