如何使用这个 simplexml_load_string 进行 foreach 循环

发布于 2024-11-18 06:05:20 字数 497 浏览 1 评论 0原文

我正在使用 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].'"'.
            '}'; 

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不奢求什么 2024-11-25 06:05:20

您仅引用每个 SimpleXMLObject 的一个实例。
例如,$xml->Date[0] 仅指第一次出现的 Date 对象。要打印所有日期对象,您需要
循环遍历它们

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

或者,您可以使用 children 函数:

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

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;
}
梦一生花开无言 2024-11-25 06:05:20
$datebuffer;
$count = 0;
foreach($xml->Date as $date){
   $count++;
   datebuffer .= "Date:".$count ." ".$date; 
}

等等...

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

and so on...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文