dirtside dirtside - 5 months ago 32
PHP Question

PHP: Removing an attribute from a DOMNode object

I've got a DOMNode object that has some attributes. $Node->attributes is a DOMNamedNodeMap, which has no methods for removing one of the entries in the map. The DOMNode class also has no methods for removing attributes from an element. I've looked through a number of the other related classes and none of them seem to provide a mechanism for removing an attribute node from its parent. (DOMNode::removeChild doesn't work; it throws a "Not found error" if I pass a DOMAttr object to it.)

Aside from constructing a new DOMNamedNodeMap and adding all the attributes to it except the one I don't want... any ideas? Thanks.


If you've got a DOMNode that has some attributes, it must be a DOMElement. In which case you should be able to call removeAttribute/removeAttributeNS/removeAttributeNode on it.

It is somewhat curious that PHP's DOMNamedNodeMap documents getNamedItem[NS] but does not acknowledge the existence setNamedItem[NS] and removeNamedItem[NS], which would have been another way of doing it.

DOMNode::removeChild can't work because a DOMAttr is not a child of another DOMNode; ‘attributes’ is a separate space to childNodes. You also can't create a new NamedNodeMap on its own to write to DOMNode::attributes, as that's a read-only property.