Reputation: 2991
I've got an XML feed that I want to pull from via PHP, here's the XML:
<PhysicalCar>
<Car IDValue="fr">
<CarInformation>
...INFORMATION...
</CarInformation>
<CarModel IDValue="lx-red">
<Name>Luxurious Frodo - Red</Name>
</CarModel>
<CarModel IDValue="kx-blue">
<Name>Kajun Frodo - Blue</Name>
</CarModel>
<CarModel IDValue="bx-purple">
<Name>BMX Frodo - Purple</Name>
</CarModel>
</Car>
<Car IDValue="gk">
<CarInformation>
...INFORMATION...
</CarInformation>
<CarModel IDValue="jr-red">
<Name>Joyride Turbo - Red</Name>
</CarModel>
<CarModel IDValue="yy-blue">
<Name>Yellow Turbo - Blue</Name>
</CarModel>
<CarModel IDValue="qq-purple">
<Name>Quilting Turbo - Purple</Name>
</CarModel>
</Car>
...MORE CARS...
</PhysicalCar>
Following the XML above, there's roughly 50-100 "Car"s. I'm trying to write PHP code that will pass in a value, for example 'gk' and scan for a "Car" with the same IDValue. WHEN found, I want to cycle through each of the "CarModel"s and echo them out.
So for example, if 'gk' was passed in, this would be the output:
JoyrideTurbo - Red, Yellow Turbo - Blue, Quilting Turbo - Purple.
Here's my php code:
<?php
$passedinvalue = 'gk';
$xml = simplexml_load_file('myxml.xml')
or die("Cannot create object");
foreach ($xml->Car as $c) {
if ($c->IDVAlue = $passedinvalue) {
foreach ($c->CarModel as $cm) {
echo $cm->Name;
}
}
}
?>
What would be the proper way to go about this PHP code?
Upvotes: 1
Views: 37
Reputation: 25965
You can solve this with XPath.
foreach($xml->xpath('//Car[@IDValue="' . $passedinvalue . '"]') as $car_models) {
foreach($car_models->CarModel as $car_model) {
echo $car_model->Name;
}
}
Upvotes: 2