我正在尝试从托管在远程服务器上的实时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";
}
答案 0 :(得分: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>';
}
}
}
}
}
答案 1 :(得分:1)
使用xpath
直接转到<carpark>
- 节点:
$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 />";