I can’t seem to parse my xml today. What have I done wrong? I’m hoping someone can point me to a better/working solution.
I want to parse a bus route xml file that looks like this:
<buses>
<bus>
<num>12</num>
<stime>05:00</stime>
<etime>22:00</etime>
<freq>?</freq>
<route>
<stop>Eonyang Bus Terminal</stop>
<stop>Chuk Hyub</stop>
<stop>Eonyang Bolim Hospital</stop>
<stop>Samnammyeong Residential Center</stop>
<stop>SinAn</stop>
</route>
</bus>
<bus>
<num>13</num>
<stime>?</stime>
<etime>?</etime>
<freq>?</freq>
<route>
<stop>KTX Ulsan Station</stop>
<stop>Driving Hagwon</stop>
<stop>Jayeon Science High School</stop>
<stop>Eonyang Bus Stop</stop>
<stop>Bolim Hospital</stop>
<stop>Daewon Green Apt.</stop>
</route>
Based on user input of origin and destination, I want to search through the list of stops to find the desired bus or buses, but simply parsing this list is not working.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("buses-new.xml");
$buses=$xmlDoc->getElementsByTagName('bus');
for($i=0; $i<($buses->length); $i++) {
$route=$buses->item($i)->getElementsByTagName('route');
$busnum=$buses->item($i)->getElementsByTagName('num');
foreach( $route->childNodes as $stop) {
$loc = $stop->nodeValue;
if (stristr($loc,$orig)) {
// found a bus with origin
$origins[$ocount]= $i;
$ocount++;
}
if (stristr($loc,$dest)) {
// found a bus with destination
$destination[$dcount] = $i;
$dcount++;
}
} // for all stops
} // for all buses
I’m getting an error on —- foreach( $route->childNodes as $stop) — says in invalid argument.
what is the right way to parse an indeterminate list of childnodes from each route?
You need to do either of the following:
If you know there is only one route element in a bus element:
Change
to
If there can be multiple route items, you need to iterate: