XPath 和 PHP:什么都不能正常工作 [英] XPath and PHP: nothing works properly
问题描述
这是我的代码:
$XML = <<<XML
<items>
<item id="123">
<name>Item 1</name>
</item>
<item id="456">
<name>Item 2</name>
</item>
<item id="789">
<name>Item 3</name>
</item>
</items>
XML;
$objSimpleXML = new SimpleXMLElement($XML);
print_r($objSimpleXML->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[1]/name'));
没什么特别的:我试图通过 XPath
提取一些数据.路径必须是一个字符串,以设计一个从 XML
配置文件加载数据的动态程序.
Nothing really special: I am trying to extract some data via XPath
. The path must be a string to design a dynamic program which loads its data from a XML
configuration file.
当使用像 $objSimpleXML->items->item[0]['id']
这样的 PHP 对象访问时,一切正常.但是 XPath
方法并没有真正起作用.上面的代码生成以下输出:
When using PHP object access like $objSimpleXML->items->item[0]['id']
everything works fine. But XPath
approach does not really work. The code above generates the following output:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 123
)
[name] => Item 1
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 456
)
[name] => Item 2
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
)
)
我同意第一个输出.但是在第二个输出中,返回的是整个元素而不是属性.为什么?并且最后一个列表是空的而不是名称内容?
I agree with the first output. But in the second output the whole element is returned instead of the attribute. Why? And the last listing is empty instead of name content?
推荐答案
这是因为你的 XPath 是错误的.您正在使用谓词,即
It's because your XPath is wrong. You're using predicates, i.e.
./item[2][@id]
这意味着具有 id
属性的第二个 item
",但它似乎是您想要的
which means "the second item
that has an id
attribute", but it appears you want
./item[2]/@id
这篇关于XPath 和 PHP:什么都不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!