Accessing @attribute from SimpleXML
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;
$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
Use SimpleXMLElement::attributes
.
Truth is, the SimpleXMLElement get_properties
handler lies big time. There's no property named "@attributes", so you can't do $sxml->elem->{"@attributes"}["attrib"]
.
Try this
$xml->attributes()->Token
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
I used before so many times for getting @attributes
like below and it was a little bit longer.
$att = $xml->attributes();
echo $att['field'];
It should be more easy and you can get attributes following format only at once:
Standard Way - Array-Access Attributes (AAA)
$xml['field'];
Other alternatives are:
Right & Quick Format
$xml->attributes()->{'field'};
Wrong Formats
$xml->attributes()->field;
$xml->{"@attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];