解析XML属性PHP

时间:2016-09-03 21:15:09

标签: php xml

我正在尝试回显每个 routeTitle 下的分钟属性。

我的输出:http://zxstudios.ca/api/test2.php

XML:http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=ttc&stopId=1974

<?php

$stopid="1974";
$urlbase = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=ttc&stopId=";
$url = $urlbase.$stopid;

$xml = simplexml_load_file($url);
$rt = $xml->predictions;

foreach ($rt as $value) {
    echo $value->attributes()->routeTitle."Min. <br>";
}

echo $rt->direction->attributes()->minutes;

?>

例如:

325-Don Mills
3 Min.
1 Min.
185-Don Mills Rocket
2 Min.
1 Min.
25-Don Mills
2 Min.
1 Min.

更新了问题:如何访问正确的节点并避免“警告:main():节点不再存在......”?

1 个答案:

答案 0 :(得分:0)

如果您想为每个 routeTitle 回显分钟属性值,那么您的foreach循环应如下所示:

// your code

foreach ($rt as $value) {
    echo $value->attributes()->routeTitle . '<br />';
    if(isset($value->direction)){
        foreach($value->direction->prediction as $attr){
            foreach($attr->attributes() as $k => $v){
                if($k == 'minutes'){
                    echo $v . ' minutes <br />';
                }
            }
        }
    }else{
        echo "No direction. <br />";
    }
}