开发者

How have foreach loop with this simplexml_load_string

开发者 https://www.devze.com 2023-03-16 09:39 出处:网络
I am parsing xml using simplexml_load_string like this : $xml = simplexml_load_string($response); echo \'{\'.

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号