Just started getting oritented with SimpleXML and have run into a problem
I am able to parse simple xml pages like below
<something>
<something2> value1 </something2>
<something3> value2 </something3>
</something>
Fairly simple to get the values of something2 and something3 if that's the only thing i need
However I am having problem with XML files that have multiple instances of a tag e.g
<car>
<carID>001</carID>
<carTyre>4</carTyre>
<carColor>Red</carColor>
<carName>Bruce</carName>
</car>
<car>
<carID>002</carID>
<carTyre>4</carTyre>
<carColor>Blue</carColor>
<carName>Tom</carName>
</car>
<car>
<carID>003</carID>
<carTyre>4</carTyre>
<carColor>Yellow</carColor>
<carName>Alex</carName>
</car>
<car>
<carID>004</carID>
<carTyre>4</carTyre>
<carColor>White</carColor>
<carName>Tina</carName>
</car>
If i only wanted specific information (not the whole data set) for e.g
Tina - White Tome - Blue
How could I do this?
Lets say that is all in the Cars.xml, then you can try something like this:
<?php
$cars = simplexml_load_file("Cars.XML");
foreach($cars->xpath('//car') as $car) {
$row = simplexml_load_string($car->asXML());
$v = $row->xpath('//carID[. ="004"]');
if($v[0]){
print $car-> carName . '-' . $car-> carColor;
}
}
?>
You can also create an xpath like //car[carID[text()="001"]]
This will give you the entire xml structure for carID with 001. You can change the ID to any other. If you want all the details under this parent node you can use some thing like this //car[carID[text()="001"]]/carTyre
This will give you the node carTyre under id 001. Hope this helps.