2011-02-06 95 views
3

如何從此XML文件獲取所有「座位」子節點及其屬性?PHP,XML - 獲取子節點及其屬性

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

我有不同的seatmaps,所以我想用一個ID 然後分配所有的「座位」節點及其變量屬性查詢得到它們。

到目前爲止,我一直在使用DOM方法,但也許simpleXML或XPath會更容易,因爲從DOMDocumet,DOMElement,DOMNode向下鑽取時,其真正的 會混淆。

任何幫助將是偉大的,歡呼聲!

回答

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

只會工作`seatmap`是第一級節點,但無論如何+1 :) – netcoder 2011-02-06 17:19:02

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