Finding the first entry of XML and displaying it

Tags: , ,

Im working on compiling a list using XML and PHP. I’m looking to find the first “destination tag” found in the RailVehicleStateClass for each train ID and echo it out. I tried doing a foreach loop to gather the destination tag but it just loops the same data for each train ID until the end of the xml file. Below is a snippet of the XML file, the full version has well over 700 entries and each train can have anywhere from 1 to 100+ railvehiclaes associated with it.


<ScnLoader xmlns:xsd="" xmlns:xsi="">
                        <destinationTag>TRC SVMS</destinationTag>


            $trains = simplexml_load_file("Auto%20Save%20World.xml") or die("Error: Cannot create object");   
            echo "<table>";
                echo "<th>#</th>";
                echo "<th>Train ID</th>";
                echo "<th>Symbol</th>";
                echo "<th>Direction</th>";
                echo "<th>AI</th>";
            foreach ($trains->xpath("//TrainLoader") as $train) {
                $totalUnitCount = $totalUnitCount + 1;

                foreach (array_slice($trains->xpath("//RailVehicleStateClass"),0,1) as $unit){
                    echo $unit->destinationTag;
                echo "</td>";
                echo "<td>";
                echo $train->DispatchTrainDirection;
                echo "</td>";
                echo "<td>";
                echo $train->TrainWasAI;
                echo "</td>";



Your xpath query to get the RailVehicleStateClass elements needs to be made relative to the current $train. You can do that using:


Note the use of . in front of // to make the path relative to the current $train element.

Source: stackoverflow