Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all attributes from DOMNode in a foreach loop

Tags:

dom

php

So this doesn't work:

        foreach ($element->attributes as $attribute) {
            $element->removeAttribute($attribute->name);
        }

If the node has 2 attributes, it only removes the first one.

I tried cloning the DOMNamedNodeMap with no success:

        $attributesCopy = clone $element->attributes;
        foreach ($attributesCopy  as $attribute) {
            $element->removeAttribute($attribute->name);
        }

Still removes only first attribute.

This issue is explained here: http://php.net/manual/en/class.domnamednodemap.php Apparently it is a feature, not a bug. But there is no solution mentioned in the comments.

like image 216
Richard Knop Avatar asked Apr 23 '12 13:04

Richard Knop


1 Answers

Simply:

$attributes = $element->attributes;
while ($attributes->length) {
    $element->removeAttribute($attributes->item(0)->name);
}

Since the attributes collection automatically reindexes as soon as an attribute is removed, just keep on removing attribute zero until none are left.

like image 143
Jon Avatar answered Oct 29 '22 13:10

Jon