How have foreach loop with this simplexml_load_string
I am parsing xml using simplexml_load_string like this :
$xml = simplexml_load_string($response);
echo '{'.
'"Date":"'.$xml->Date[0].'",'.
'"Description":"'.$xml->ShipTos->ShipTo->Ship开发者_运维技巧pingGroups->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?
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;
}
$datebuffer;
$count = 0;
foreach($xml->Date as $date){
$count++;
datebuffer .= "Date:".$count ." ".$date;
}
and so on...
精彩评论