Trouble treversing XML with simple xml

Hi,

I am having trouble traversing an XML file to get the data I want using simple xml with PHP

XML file:
https://maps.googleapis.com/maps/api/directions/xml?origin=61+-+65+Wentworth+Ave%2C+Sydney&key=AIzaSyCLFuUAdybqWbIOEJoyYLgf9Y3-MjtKu3s&destination=10+Norbrik+Dr&mode=transit&alternatives=true

What I want to do is extract each (line short_name or name) and each (line vehicle name or vehicle type

My code only gives me the first 607x Bus | but there are several
1) <short_name>607x</short_name>
2) <short_name>M20</short_name>
3) <short_name>T66</short_name>
4) <short_name>T64</short_name>


function build_transit_details($xml_obj){
	
	$transport = "";
	
	foreach($xml_obj->route->leg->step as $key => $val){
		if(isset($val->transit_details->line)){
			
			if(isset($val->transit_details->line->short_name)){
				$transport .= $val->transit_details->line->short_name." ";
			}elseif(isset($val->transit_details->line->name)){
				$transport .= $val->transit_details->line->name." ";
			}
			
			if(isset($val->transit_details->line->vehicle->name)){
				$transport .= $val->transit_details->line->vehicle->name." | ";
			}elseif(isset($val->transit_details->line->vehicle->type)){
				$transport .= $val->transit_details->line->vehicle->type." | ";
			}

		}
	}
	
	echo $transport;
	
}

Open in new window

Jeremy LeysTechnical LeadAsked:
Who is Participating?
 
Jeremy LeysTechnical LeadAuthor Commented:
Found the issue myself, I wasn't iterating through route, needed a nested foreach

function build_transit_details($xml_obj){
	
	$transport = "";
	
	if(isset($xml_obj->route)){
	
		foreach($xml_obj->route as $k => $v){
			
			if(isset($v->leg->step)){
				
				foreach($v->leg->step as $key => $val){
					if(isset($val->transit_details->line)){

						if(isset($val->transit_details->line->short_name)){
							$transport .= $val->transit_details->line->short_name." ";
						}elseif(isset($val->transit_details->line->name)){
							$transport .= $val->transit_details->line->name." ";
						}

						if(isset($val->transit_details->line->vehicle->name)){
							$transport .= $val->transit_details->line->vehicle->name." | ";
						}elseif(isset($val->transit_details->line->vehicle->type)){
							$transport .= $val->transit_details->line->vehicle->type." | ";
						}

					}
				}
			
			}

		}
	
	}
	
	echo $transport;
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.