Reputation: 1571
I'm trying to get call an XML array using PHP, but for whatever reason, it is not providing results properly. The XML looks like this as a simpleXMLElement.
SimpleXMLElement Object ( [@attributes] => Array ( [copyright] => All data copyright 2012. )
[route] => SimpleXMLElement Object
(
[@attributes] => Array
(
[tag] => 385
[title] => 385-Sheppard East
[color] => ff0000
[oppositeColor] => ffffff
[latMin] => 43.7614499
[latMax] => 43.8091799
[lonMin] => -79.4111
[lonMax] => -79.17073
)
[stop] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[tag] => 14798
[title] => Sheppard Ave East At Yonge St (Yonge Station)
[lat] => 43.7614499
[lon] => -79.4111
[stopId] => 15028
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[tag] => 4024
[title] => Sheppard Ave East At Doris Ave
[lat] => 43.7619499
[lon] => -79.40842
[stopId] => 13563
)
)
There are several parts to the stop array. My code looks like this:
$url = "this_url";
$content = file_get_contents($url);
$xml = new SimpleXMLElement($content);
$route_array = $xml->route->stop;
When I print the $route_array, it only shows 1 record from the stops. Do I need to run this through a loop? Normally when I do this in JSON, it works fine. I'd like to get everything in the stop array only.
Thanks in advance to all of you experts out there helping out a beginner like myself
Upvotes: 1
Views: 54
Reputation: 64526
Using print_r
on SimpleXML elements does not always give you the full picture. Your elements are there but aren't shown.
$xml->route->stop
is an array of <stop>
tags within <route>
. So if you want to loop through each stop tag then:
foreach($xml->route->stop as $stop)
{
echo (string)$stop; // prints the value of the <stop> tag
}
In the loop, $stop
is a SimpleXML element, so in order to print its value you can cast the whole element as a string using the (string)
syntax. You can still access attributes and other SimpleXML element properties.
If you know which <stop>
element you want to target, then you can get it directly:
echo (string)$xml->route->stop[1]; // prints the second <stop> value
Upvotes: 1