开发者

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 b开发者_如何学Ce great, cheers!


$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']
}


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');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜