php xpath problems

≡放荡痞女 提交于 2019-12-07 01:00:25

问题


I am trying to parse a blogspot feed using xpath but it doesnt seem to be working with anything that I try. I am not sure if it is because of the namespaces or what but I was hoping someone could help me. Here is the code:

    $xml = simplexml_load_file('http://feeds.feedburner.com/blogspot/MKuf');

$next = $xml->xpath("//link[@rel='next']");
print_r($next);

This is just returning an empty array and it should not be. I tried it doing just link or just entry and it still is returning empty. The only one I can run on it that works is *. Any help is appreciated.


回答1:


Like already said in the comment to you question, the document has a default namespace which you have to register before you can query it with XPath.

Since the linked duplicate only shows how to do it with DOM, I'll add an SimpleXml example

$feed = simplexml_load_file('http://feeds.feedburner.com/blogspot/MKuf');
$feed->registerXPathNamespace('f', 'http://www.w3.org/2005/Atom');
foreach ($feed->xpath('//f:link[@rel="next"]') as $link) {
    var_dump($link);
}

Manual Page: http://de.php.net/manual/de/simplexmlelement.registerxpathnamespace.php

Live Demo




回答2:


As Gordon said, you need to register the XML document's default namespace, like this:

$xml->registerXPathNamespace('default', 'http://www.w3.org/2005/Atom');

And then use the default prefix to refer to normal elements:

$next = $xml->xpath("//default:link[@rel='next']");

Newer versions may allow you to define the default ('') namespace. See http://www.qc4blog.com/?p=281 for more information.



来源:https://stackoverflow.com/questions/5354345/php-xpath-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!