Problems with php xpath

I am trying to parse the blogspot feed using xpath, but it does not seem to work with anything I'm trying. I'm not sure if this is due to 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); 

It just returns an empty array, and it should not be. I tried to make it just a link or just a record, and it still returns empty. The only one I can work with is *. Any help is appreciated.

+6
php xpath simplexml
source share
2 answers

As already mentioned in the commentary on you, the document has a default namespace that you must register before you can request it using XPath.

Since the linked duplicate only shows how to do this with the DOM, I will add a 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

+10
source share

As Gordon said, you need to register the default XML namespace, for example:

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

And then use the default prefix to denote common elements:

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

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

+3
source share

All Articles