Removing all attributes from DOMNode in a foreach loop is not a good idea
2012 May 16
So few days ago in work I needed to remove all attributes from a DOMNode instance while parsing an XML response from a web service. Naively, I wrote a code like this:
-
foreach ($element->attributes as $attribute) {
-
$element->removeAttribute($attribute->name);
-
}
It turns out that the attributes collection is reindexed each time you remove an attribute. So the code above would delete only the first attribute in a case the node had 2 attributes, it would only remove first two attributes if the node had 4 attributes and so on.
The correct way to do this:
-
while ($element->attributes->length) {
-
$element->removeAttribute($element->attributes->item(0)->name);
-
}
No comments yet