سؤال

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

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top