2013-04-18 78 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'),但这似乎并不是你想要的。