Reputation: 632
How do i get all the "seat" child nodes and their attributes from this XML file?
<seatmap id="1">
<seat row="A" seatnum="01" available="1" />
<seat row="A" seatnum="02" available="1" />
<seat row="A" seatnum="03" available="1" />
<seat row="A" seatnum="04" available="1" />
<seat row="A" seatnum="05" available="1" />
</seatmap>
I have different seatmaps, so i want to get them by querying with an ID then assigning all the 'seat' nodes and their attributes to variables.
I've been using DOM methods so far, but maybe simpleXML or XPath would be easier as its really confusing as you drill down from DOMDocumet, DOMElement, DOMNode.
Any help would be great, cheers!
Upvotes: 5
Views: 7446
Reputation:
$XML = <<<XML
<parent>
<seatmap id="1">
<seat row="A" seatnum="01" available="1" />
<seat row="A" seatnum="02" available="1" />
<seat row="A" seatnum="03" available="1" />
<seat row="A" seatnum="04" available="1" />
<seat row="A" seatnum="05" available="1" />
</seatmap>
</parent>
XML;
$xml_nodes = new SimpleXMLElement($XML);
$nodes = $xml_nodes->xpath('//seatmap[@id = "1"]/seat'); // Replace the ID value with whatever seatmap id you're trying to access
foreach($nodes as $seat)
{
// You can then access: $seat['row'], $seat['seatnum'], $seat['available']
}
Upvotes: 6
Reputation: 67695
Easily can be done with DOM:
$dom = new DOMDocument;
$dom->load('xmlfile.xml');
$xpath = new DOMXPath($dom);
$seats = $xpath->query('//seatmap[@id="1"]/seat');
if ($seats->length) {
foreach ($seats as $seat) {
echo "row: ".$seat->getAttribute('row').PHP_EOL;
echo "seatnum: ".$seat->getAttribute('seatnum').PHP_EOL;
echo "available: ".$seat->getAttribute('available').PHP_EOL;
}
} else {
die('seatmap not found or is empty');
}
Upvotes: 1