1

I am parsing xml using simplexml_load_string like this :

 $xml = simplexml_load_string($response);

        echo '{'.
            '"Date":"'.$xml->Date[0].'",'.
            '"Description":"'.$xml->ShipTos->ShipTo->ShippingGroups->ShippingGroup->OrderItems->OrderItem->Description[0].'",'. 
            '"Track":"'.$xml->Shipments->Shipment->Track[0].'"'.
            '}'; 

This works ok but if a node appears in the xml multiple times it only grabs it once. Can someone please help me understand how I would write a foreach loop specifically for the Description node?

2
  • simple_xml tends to make things, IMO harder to process, have you tried DOMDocument? $dates = $doc->getElementsByTagName("Date"); foreach( $dates as $date ) { } ? Commented Jun 30, 2011 at 23:25
  • no, thanks jeremy i will investigate Commented Jun 30, 2011 at 23:53

2 Answers 2

5

You are only referring to one instance of each SimpleXMLObject. For example $xml->Date[0] refers to the first occurence of a Date object only. To print all Date objects you need to loop through them

foreach( $xml->Date as $date ){
   print (string)$date;
}

Alternatively, you could use the children function:

foreach( $xml->children('Date') as $date ){
   print (string)$date;
}
Sign up to request clarification or add additional context in comments.

Comments

1
$datebuffer;
$count = 0;
foreach($xml->Date as $date){
   $count++;
   datebuffer .= "Date:".$count ." ".$date; 
}

and so on...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.