2013-04-18 143 views
0

這是XML的一個片段,我的工作:的SimpleXML不能訪問兒童

<category name="pizzas"> 
    <item name="Tomato &amp; Cheese"> 
     <price size="small">5.50</price> 
     <price size="large">9.75</price> 
    </item> 
    <item name="Onions"> 
     <price size="small">6.85</price> 
     <price size="large">10.85</price> 
    </item> 
    <item name="Peppers"> 
     <price size="small">6.85</price> 
     <price size="large">10.85</price> 
    </item> 
    <item name="Broccoli"> 
     <price size="small">6.85</price> 
     <price size="large">10.85</price> 
    </item> 
</category> 

這是我的PHP是什麼樣子:

$xml = $this->xml; 
$result = $xml->xpath('category/@name'); 
foreach($result as $element) { 
    $this->category[(string)$element] = $element->xpath('item'); 
} 

一切工作正常,除了$元素 - >的xpath( '項目');我也試過使用:$ element-> children();以及其他xpath查詢,但它們都返回null。 爲什麼我無法訪問某個類別的孩子?

+4

夥計,使用'category/item' – ajreal

回答

1

它看起來像你試圖建立一個基於類別的樹,按類別名稱。要做到這一點,你需要改變你的代碼看起來像這樣:

$xml = $this->xml; 

//Here, match the category tags themselves, not the name attribute. 
$result = $xml->xpath('category'); 
foreach($result as $element) { 
    //Iterate through the categories. Get their name attributes for the 
    //category array key, and assign the item xpath result to that. 
    $this->category[(string)$element['name']] = $element->xpath('item'); 
} 

在此處與自己原來的代碼:$result = $xml->xpath('category/@name');你的結果是name屬性節點,其中,作爲屬性,不能有孩子。

現在,如果您只是想要一個所有項目的列表,您可以使用$xml->xpath('category/items'),但這似乎並不是你想要的。