PHP回显来自XML文档的对象,其中存在重复的节点

时间:2014-07-14 14:03:46

标签: php xml

我一直在使用Bing Maps API 来获取某个地区的交通事故。然后,这将创建一个XML文档,我可以访问单个节点的对象,但不能回显嵌套在其他节点中的任何节点。 XML文档如下所示:

<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>
 - Message -
</Copyright>
<BrandLogoUri>
  - Logo -
 </BrandLogoUri>
 <StatusCode>200</StatusCode>
 <StatusDescription>OK</StatusDescription>
 <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
 <TraceId>
  - Trace ID- 
 </TraceId>
 <ResourceSets>
 <ResourceSet>
 <EstimatedTotal>1</EstimatedTotal>
 <Resources>
 <TrafficIncident>
 <Point>
 <Latitude> - Latitude - </Latitude>
 <Longitude>- Longitude -</Longitude>
 </Point>
 <IncidentId>- IncidentId -</IncidentId>
 <LastModifiedUTC>- Time -</LastModifiedUTC>
 <StartTimeUTC>- Time -</StartTimeUTC>
 <EndTimeUTC>- Time -</EndTimeUTC>
 <Type>- Type -</Type>
 <Severity>- Severity -</Severity>
 <Verified>- True -</Verified>
 <RoadClosed>- True -</RoadClosed>
 <Description>
  - Description - 
 </Description>
 <ToPoint>
 <Latitude>-Latitude -</Latitude>
 <Longitude>- Longitude -</Longitude>
 </ToPoint>
 </TrafficIncident>
 </Resources>
 </ResourceSet>
 </ResourceSets>
 </Response>

要在单个节点中回显对象,我一直在使用以下PHP代码:

<?php 
    $xml = simplexml_load_file("link");
    echo "Trace Id <br>";
    echo $xml->TraceId . "<br>";
    echo $xml->Copyright . "<br>";
    echo $xml->Verified . "<br>";
?>

为了回显嵌套节点中的Latitude,我尝试了PHP代码:

    foreach( $xml->TrafficIncident->Point->Latitude as $row ){
        echo'<td>'.$row.'</td>';
    }

但到目前为止还没有运气。任何想法?

1 个答案:

答案 0 :(得分:0)

试试这个:

foreach($xml->ResourceSets->ResourceSet->Resources->TrafficIncident as $trafficIncident)
{
   echo $trafficIncident->Point->Latitude.' '.$trafficIncident->Point->Longitude;
}