I am having a problem accessing the @attribute
section of my SimpleXML object. When I var_dump
the entire object, I get the correct output, and when I var_dump
the rest of the object (the nested tags), I get the correct output, but when I follow the docs and var_dump
$xml->OFFICE->{'@attributes'}
, I get an empty object, despite the fact that the first var_dump
clearly shows that there are attributes to output.
Anyone know what I am doing wrong here/how I can make this work?
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:
$xml['field'];
Other alternatives are:
$xml->attributes()->{'field'};
$xml->attributes()->field;
$xml->{"@attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];
$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"]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With