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

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


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


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


I've stumbled upon this question while searching for a way to convert node attributes to an array in order to compare that array against results from database. Answer from https://stackoverflow.com/users/264502/jan-molak does do the trick, but for my case it does not account for the fact, that some attributes may be missing in the node or that they may be empty strings, while there are NULLs returned from DB.
To cover this I've expanded it into below function, that may be of use to someone else, as well:

    #Function to convert DOMNode into array with set of attributes, present in the node    #$null will replace empty strings with NULL, if set to true    #$extraAttributes will add any missing attributes as NULL or empty strings. Useful for standartization    public function attributesToArray(\DOMNode $node, bool $null = true, array $extraAttributes = []): array    {        $result = [];        #Iterrate attributes of the node        foreach ($node->attributes as $attrName => $attrValue) {            if ($null && $attrValue === '') {                #Add to resulting array as NULL, if it's empty string                $result[$attrName] = NULL;            } else {                #Add actual value                $result[$attrName] = $attrValue->textContent;            }        }        #Add any additional attributes, that are expected        if (!empty($extraAttributes)) {            foreach ($extraAttributes as $attribute) {                if (!isset($result[$attribute])) {                    if ($null) {                        #Add as NULL                        $result[$attribute] = NULL;                    } else {                        #Or add as empty string                        $result[$attribute] = '';                    }                }            }        }        #Return resulting string        return $result;    }}

I've replaced nodeValue with textContent, because somehow it feels a bit more "natural" to me, when speaking about attributes, but technically they will be the same here regardless.
If required, this function is avialable in Composer as part of Simbiat/ArrayHelpers (https://github.com/Simbiat/ArrayHelpers)