PHP, XML - Get child nodes and their attributes

How to get all the child seats 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 cards for sitting, so I want to get them by requesting an identifier, then assigning “nodes” and their attributes to all nodes.

I have been using DOM methods so far, but maybe simpleXML or XPath would be simpler, since it is really confusing when you are looking at DOMDocumet, DOMElement, DOMNode.

Any help would be great, cheers!

+3
source share
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']
}
+4
source

Easily done with the 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');
}
+1
source

Source: https://habr.com/ru/post/1790321/


All Articles