0

I know the answer for this will be incredibly simple but it's one of those problems that I can't seem to solve using google/SO because it deals with a character that's hard to search for. I'm getting an xml from a rest api using php. I've used simple_xml_load_string($string) and now when I print_r I get this:

SimpleXMLElement Object
(
    [Seaports] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [Id] => 8675309
                            [Name] => CHORIZON WIRELUSS
                        )                                           
                    [Statistics] => SimpleXMLElement Object
                        (
                            [Clicks] => 194

                        )

etc

Let's say I want

$xml->Seaports[0]->@attributes['Id']

echo $xml->Seaports[0]->@attributes['Id']; 

gives me a syntax error and

echo $xml->Seaports[0]->attributes['Id'];

What am I doing wrong?

pg.
  • 2,503
  • 4
  • 42
  • 67
  • How are you doing this? Also what error do you get when you add it? – PeeHaa Apr 30 '13 at 22:35
  • possible duplicate of [simplexml\_load\_file can't parse \[@attributes\] => Array](http://stackoverflow.com/questions/7360856/simplexml-load-file-cant-parse-attributes-array) or better [Accessing @attribute from SimpleXML](http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) and [How to access element attributes with SimpleXml?](http://stackoverflow.com/q/4625045/367456) – hakre Apr 30 '13 at 23:26
  • Oh damn, just found this http://stackoverflow.com/questions/7523044/access-attributes-data-in-simplexmlelement-in-php – pg. Apr 30 '13 at 23:27
  • @p.g. can happen. Better search for dupes with something common (e.g. simplexml) most often the older answers are of better quality. I rarely add good new content, I even extend older Q&As more and more often. – hakre Apr 30 '13 at 23:28

1 Answers1

1

This is a SimpleXMLElement object. The '@attributes' row is an internal representation of the attributes from the XML element. Use SimpleXML's functions to get data from this object rather than interacting with it directly. Or, a kind of hacky way is to cast it to an array like this:

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

 //- grab the value of '@attributes' key, which contains the array your after
 $atts_array = $atts_array['@attributes'];

 var_dump($atts_array);
dave
  • 62,300
  • 5
  • 72
  • 93