Search code examples
phpxmlsimplexml

PHP SimpleXML Parsing elements with multiple attributes


I have to parse data from a web service that returns XML through php. I have no issues with getting the data but I am having trouble accessing a specific attribute. The xml I am parsing looks like this when I var_dump it.

object(SimpleXMLElement)#13 (2) { ["@attributes"]=> array(1) { ["Label"]=> string(4) "11am" } ["Value"]=> object(SimpleXMLElement)#14 (1) { ["@attributes"]=> array(1) { ["Y"]=> string(6) "204.68" } } }

To get that element I am looping through the xml and each element is like this

foreach($details as $key){
    foreach($key as $value){
        var_dump($value);           
    }
}

To access the Label part of the element I can just echo $value['Label'] but I am having trouble accessing the Y element. Any help would be very much appreciated!


Solution

  • The Y attribute is on the Value element, which is a child node underneath your current node. That means there is a separate SimpleXMLElement object on $value. You can access them both in your foreach loop like so:

    foreach($details as $key){
      foreach($key as $value){
        $label = $value['Label'];
        $y = $value->Value['Y'];
      }
    }