Php SimpleXml可以';无法接触儿童

Php SimpleXml可以';无法接触儿童,php,simplexml,Php,Simplexml,这是我正在使用的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">

这是我正在使用的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>
除了$element->xpath('item'),一切正常; 我还尝试使用:$element->children();以及其他xpath查询,但它们都返回null。
为什么我不能访问类别的子级?

看起来您正在尝试基于类别构建一个树,并按类别名称键入。为此,您应该将代码更改为如下所示:

$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')
,但这似乎不是您想要的。

dude,使用
category/item
$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');
}