Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get all of a DOMElement's attributes?

I'm reading some XML with PHP and currently using the DOMDocument class to do so. I need a way to grab the names and values of a tag's (instance of DOMElement) attributes, without knowing beforehand what any of them are. The documentation doesn't seem to offer anything like this. I know that I can get an attribute's value if I have its name, but again, I don't know either of these and need to find both.

I also know that other classes like SimpleXMLElement have this capability, but I'm interested in how it can be done with DOMDocument.

like image 643
Josh Leitzel Avatar asked Aug 27 '09 03:08

Josh Leitzel


People also ask

How do I get DOM attributes?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.


2 Answers

If you want to get attribute name and attribute values (not the attributeNodes) you have to call the $attrNode->nodeValue property of the DOMNode object.

$attributes = array();

foreach($element->attributes as $attribute_name => $attribute_node)
{
  /** @var  DOMNode    $attribute_node */
  $attributes[$attribute_name] = $attribute_node->nodeValue;
}
like image 86
Jan Molak Avatar answered Oct 20 '22 13:10

Jan Molak


You can get all the attributes of a given DomNode, using the DomNode->attributes property, it will return you DOMNamedNodeMap containing the attribute names and values.

foreach ($node->attributes as $attrName => $attrNode) {
    // ...
}
like image 41
Christian C. Salvadó Avatar answered Oct 20 '22 12:10

Christian C. Salvadó