与 DOM 不同,SimpleXML 没有文档对象的概念,只有元素的概念。因此,如果加载 XML,您总是会获得文档元素。
$feed = simplexml_load_file($xmlFile);
var_dump($feed->getName());
Output:
string(4) "feed"
这意味着所有 Xpath 表达式都必须相对于该元素或绝对。简单的feed
将不起作用,因为上下文已经是feed
元素。
但这还有另一个原因。 URL 是 Atom 提要。所以命名空间中的 XML 元素http://www.w3.org/2005/Atom
。 SimpleXML 的神奇语法可以识别某些调用的默认名称空间 - 但 Xpath 不能。这里不是 Xpath 中的默认命名空间。您必须使用前缀注册它们,并在 Xpath 表达式中使用该前缀。
$feed = simplexml_load_file($xmlFile);
$feed->registerXpathNamespace('a', 'http://www.w3.org/2005/Atom');
foreach ($feed->xpath('/a:feed/a:entry[position() < 3]') as $entry) {
var_dump((string)$entry->title);
}
Output:
string(24) "Sharing the goals around"
string(34) "Kouyate inspires Hammers' comeback"
然而,在 SimpleXML 中,必须为您调用的每个对象完成注册xpath()
方法上。
将 Xpath 与 DOM 结合使用略有不同,但功能更强大。
$document = new DOMDocument();
$document->load($xmlFile);
$xpath = new DOMXpath($document);
$xpath->registerNamespace('a', 'http://www.w3.org/2005/Atom');
foreach ($xpath->evaluate('/a:feed/a:entry[position() < 3]') as $entry) {
var_dump($xpath->evaluate('string(a:title)', $entry));
}
Output:
string(24) "Sharing the goals around"
string(34) "Kouyate inspires Hammers' comeback"
使用 with 的 Xpath 表达式DOMXpath::evaluate()
可以返回标量值。