Zedkay22 Zedkay22 - 3 months ago 8
PHP Question

Parsing XML Attributes PHP

I'm attempting to echo the minutes attribute under each routeTitle.

My output: 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;

?>


So for example:

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


Updated question: how do I access the correct node and avoid "Warning: main(): Node no longer exists..." ?

Answer

If you want to echo minutes attribute values for each routeTitle, then your foreach loop should be like this:

// 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 />";
    }
}