PHP,XML - 获取子节点及其属性

时间:2011-02-06 17:09:30

标签: php xml dom codeigniter

如何从此XML文件中获取所有“seat”子节点及其属性?

   <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>

我有不同的座位图,所以我想通过查询ID来获取它们 然后将所有“座位”节点及其属性分配给变量。

到目前为止,我一直在使用DOM方法,但也许simpleXML或XPath会更容易 从DOMDocumet,DOMElement,DOMNode向下钻取时会感到困惑。

任何帮助都会很棒,欢呼!

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

可以使用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');
}