foreach如何循环使用这个simplexml_load_string

Zac*_*Zac 1 php xml simplexml

我正在使用simplexml_load_string解析xml,如下所示:

 $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].'"'.
            '}'; 
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,但如果一个节点多次出现在xml中,它只会抓取一次.有人可以帮我理解如何专门为Description节点编写foreach循环吗?

bri*_*n_d 5

您只是指每个实例SimpleXMLObject.例如,$xml->Date[0]仅指Date对象的第一次出现.要打印所有Date对象,需要循环它们

foreach( $xml->Date as $date ){
   print (string)$date;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下children功能:

foreach( $xml->children('Date') as $date ){
   print (string)$date;
}
Run Code Online (Sandbox Code Playgroud)