Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing @attribute from SimpleXML

Tags:

php

xml

simplexml

People also ask

How to read XML attribute value in PHP?

PHP SimpleXML - Get Node Values of Specific Elements$xml=simplexml_load_file("books. xml") or die("Error: Cannot create object"); echo $xml->book[0]->title .

How get data from XML URL in PHP?

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA); $url can be php file, as long as the file generate xml format data as output.

What are attributes in PHP?

Attributes are kinds of classes that can be used to add metadata to other classes, functions, class methods, class properties, constants, and parameters. Attributes do nothing during runtime. Attributes have no impact on the code, but available for the reflection API.


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'];

$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"].