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

北战南征 提交于 2020-01-02 01:11:14

问题


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.


回答1:


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) {
    // ...
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/1338692/is-there-a-way-to-get-all-of-a-domelements-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!