Hey guys,
I work heavily on YouTube and simply need to grab my subscriber count and display it externally.
I assume PHP can help me with this.
Could anyone tell a PHP newb how to simply display this on a page?
Any help much appreciated, thanks.
| SitePoint Sponsor |
Hey guys,
I work heavily on YouTube and simply need to grab my subscriber count and display it externally.
I assume PHP can help me with this.
Could anyone tell a PHP newb how to simply display this on a page?
Any help much appreciated, thanks.
Check out the API.
I'm not at my workstation at the moment, so have no access to an IDE, but it should go something along the lines of...
PHP Code:<?php
function getYouTubeSubscriberCount($user)
{
$data = file_get_contents(sprintf('http://gdata.youtube.com/feeds/api/users/%s', $user));
$matches = array();
preg_match('~subscriberCount="(?<count>\d)"~', $data, $matches);
return isset($matches[0]['count']) ? $matches[0]['count'] : false ;
}
echo getYouTubeSubscriberCount('sonybmg'); #181218
?>Off Topic:
Edit: Just for reference, I didn't use native XML objects as I have no IDE and no memory...
@AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.
I put that into a .php file, and uploaded, and its blank
On the YouTube API PHP area on This Page, under the "Retrieving a user's profile" shows subscribers. How would I put this into a .php file?
Ah, tell you what, I'll have another stab at it. Bear in mind though, you should probably be using SimpleXML or DOM to parse the response properly.
PHP Code:<?php
function getYouTubeSubscriberCount($user)
{
$data = file_get_contents(sprintf('http://gdata.youtube.com/feeds/api/users/%s', $user));
$matches = array();
preg_match("~subscriberCount='(?<count>\d+)'~", $data, $matches);
return isset($matches['count']) ? $matches['count'] : 0 ;
}
echo getYouTubeSubscriberCount('sonybmg'); #181218
?>
@AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.





You can also use this: http://framework.zend.com/download/gdata/
Disclaimer: I haven't used it myself.
You can also get at the data in JSON format:
PHP Code:$name = 'sitepoint';
$url = sprintf('http://gdata.youtube.com/feeds/api/users/%s?alt=json', urlencode($name));
$json = @file_get_contents($url); // Naughty @-operator, use proper error handling
$data = json_decode($json, TRUE);
$count = (int) $data['entry']['yt$statistics']['subscriberCount'];
echo $count;
Bookmarks