Can't access XML node via xpath() (YT channel feed)

心不动则不痛 提交于 2019-12-11 05:34:21

问题


Very stumped by this one. In PHP, I'm fetching a YouTube user's vids feed and trying to access the nodes, like so:

$url = 'http://gdata.youtube.com/feeds/api/users/HCAFCOfficial/uploads';
$xml = simplexml_load_file($url);

So far, so fine. Really basic stuff. I can see the data comes back by running:

echo '<p>Found '.count($xml->xpath('*')).' nodes.</p>'; //41
echo '<textarea>';print_r($xml);echo '</textarea>';

Both print what I would expect, and the print_r replicates the XML structure.

However, I have no idea why this is returning zero:

echo '<p>Found '.count($xml->xpath('entry')).'"entry" nodes.</p>';

There blatantly are entry nodes in the XML. This is confirmed by running:

foreach($xml->xpath('*') as $node) echo '<p>['.$node->getName().']</p>';

...which duly outputs "[entry]" 25 times. So perhaps this is a bug in SimpleXML? This is part of a wider feed caching system and I'm not having any trouble with other, non-YT feeds, only YT ones.

[UPDATE]

This question shows that it works if you do

count($xml->entry)

But I'm curious as to why count($xml->xpath('entry')) doesn't also work...

[Update 2]

I can happily traverse YT's anternate feed format just fine:

http://gdata.youtube.com/feeds/base/users/{user id}/uploads?alt=rss&v=2


回答1:


This is happening because the feed is an Atom document with a defined default namespace.

<feed xmlns="http://www.w3.org/2005/Atom" ...

Since a namespace is defined, you have to define it for your xpath call too. Doing something like this works:

$url = 'http://gdata.youtube.com/feeds/api/users/HCAFCOfficial/uploads';
$xml = simplexml_load_file($url);
$xml->registerXPathNamespace('ns', 'http://www.w3.org/2005/Atom');
$results = $xml->xpath('ns:entry');
echo count($results);

The main thing to know here is that SimpleXML respects any and all defined namespaces and you need to handle them accordingly, including the default namespace. You'll notice that the second feed you listed does not define a default namespace and so the xpath call works fine as is.



来源:https://stackoverflow.com/questions/22880348/cant-access-xml-node-via-xpath-yt-channel-feed

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