0

这是我正在使用的 XML 片段:

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

一切正常,除了 $element->xpath('item'); 我也尝试过使用: $element->children(); 以及其他 xpath 查询,但它们都返回 null。为什么我不能访问某个类别的子项?

4

1 回答 1

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');您的结果是名称属性节点,作为属性,不能有子节点。

现在,如果您只是想要一个所有项目的列表,您可以使用$xml->xpath('category/items'),但这似乎不是您想要的。

于 2013-04-18T06:42:16.480 回答