Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, XML - Get child nodes and their attributes

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!

like image 317
Mark Avatar asked Feb 06 '11 17:02

Mark


2 Answers

$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']
}
like image 80
Tim Cooper Avatar answered Oct 24 '22 17:10

Tim Cooper


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');
}
like image 38
netcoder Avatar answered Oct 24 '22 17:10

netcoder