I'm trying to get the $xml->entry->yt:statistics->attributes()->viewCount
attribute, and I've tried some stuff with SimpleXML, and I can't really get it working!
Attempt #1
<?php
$xml = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos?author=Google");
echo $xml->entry[0]->yt:statistics['viewCount'];
?>
Attempt #2
<?php
$xml = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos?author=Google");
echo $xml->entry[0]->yt:statistics->attributes()->viewCount;
?>
Both of which return blank, though SimpleXML is working, I tried to get the feed's title, which worked!
Any ideas?
I've looked at loads of other examples on SO and other sites, but somehow this isn't working? does PHP recognize the ':' to be a cut-off, or am I just doing something stupid?
Thank you, any responses greatly appreciated!
The
yt:
prefix marks that element as being in a different "XML namespace" from the rest of the document. You have to tell SimpleXML to switch to that namespace using the->children()
method.The line you were attempting should actually look like this:
To break this down:
(string)
- this is just a good habit: you want the string contents of the attribute, not a SimpleXML object representing it$xml->entry[0]
- as expected->children('yt', true)
- switch to the namespace with the local alias 'yt'->statistics
- as expected->attributes(NULL)
- technically, the attribute "viewCount" is back in the default namespace, because it is not prefixed with "yt:", so we have to switch back in order to see it->viewCount
- running->attributes()
gives us nothing but attributes, which are accessed with->foo
not['foo']
If you just want to get the viewcount of a youtube video then you have to specify the video ID. The youtube ID is found in each video url. For example "http://www.youtube.com/watch?v=ccI-MugndOU" so the id is ccI-MugndOU. In order to get the viewcount then try the code below
I would use the gdata component from the zend framework. Is also available as a separate module, so you don't need to use the whole zend.