2

我正在尝试从托管在远程服务器上的实时 XML 文档中提取数据。我正在尝试使用 PHP 来做到这一点。

XML文件的布局是这样的:

<carparkData>
<Northwest>
<carpark name="PARNELL" spaces="51"></carpark>
<carpark name="ILAC" spaces=" "></carpark>
<carpark name="JERVIS" spaces="616"></carpark>
<carpark name="ARNOTTS" spaces="170"></carpark>
</Northwest>
<Northeast>
<carpark name="MARLBORO" spaces="185"></carpark>
<carpark name="ABBEY" spaces="97"></carpark>
</Northeast>
<Southwest>
<carpark name="THOMASST" spaces="193"></carpark>
<carpark name="C/CHURCH" spaces="51"></carpark>
</Southwest>
<Southeast>
<carpark name="SETANTA" spaces=" "></carpark>
<carpark name="DAWSON" spaces="113"></carpark>
<carpark name="TRINITY" spaces="178"></carpark>
<carpark name="GREENRCS" spaces="446"></carpark>
<carpark name="DRURY" spaces="562"></carpark>
<carpark name="B/THOMAS" spaces="168"></carpark>
</Southeast>
</carparkData>

使用 PHP 我尝试首先提取数据,然后创建一个循环来捕获<carpark>标签内包含的属性:

<?php

$data = simplexml_load_file('http://www.dublincity.ie/dublintraffic/cpdata.xml.');

foreach ($data->carpark[0]->attributes() as $a => $b) 
{
        echo $a,'="',$b,"\"\n";
}
4

2 回答 2

1

截至目前,您还没有遍历carparks. 这可能会为您指明正确的方向:

$data = simplexml_load_file('http://www.dublincity.ie/dublintraffic/cpdata.xml');

if($sectors = $data->children()){
    foreach($sectors as $sector){
        echo '<h1>'.$sector->getName().'</h1>';
        if($carparks = $sector->children()){
            foreach($carparks as $carpark){
                if($attributes = $carpark->attributes()){
                    foreach($attributes as $key=>$value){
                        echo $key.': '.$value.'<br>';
                    }
                    echo '<hr>';
                }
            }
        }
    }
}
于 2013-04-24T15:36:14.310 回答
1

用于直接xpath访问<carpark>-nodes:

$xml = simplexml_load_string($x); // assume XML in $x

$carparks = $xml->xpath("//carpark");

foreach ($carparks as $carpark) 
    echo $carpark['name'] . " has " . $carpark['spaces'] . " spaces.<br />";

看到它工作:http ://codepad.viper-7.com/JUB4Jp

于 2013-04-24T16:22:20.793 回答