While writing a custom CMS for a client, I was approached with the request to enable it to accept any YouTube URL and add that video to a video gallery page on the web site. This turned out to be a lot easier than it sounds, and in this post I'm sharing the class I wrote to assist with the task.
Download It
Click below to download the file.
Free to download, modify, and use
Download (1.3kb, PHP File)
What Does It Do?
The class contains two methods (or functions if you're a beginner):
- getVideoID($url) - Pass in any YouTube URL, the kind a client might copy and paste from the YouTube web site, and it will return the 11 character YouTube ID.
- getVideoDetails($id) - Pass in a YouTube video ID, like the one acquired using the method above, and it will return the Title, Description, and Thumbnail information from YouTube, as an array.
See The Code
class SimpleYouTube {
// will parse the youtube URL passed to it and return
// an 11 character youtube ID
function getVideoID($url)
{
// make sure url has http on it
if(substr($url, 0, 4) != "http") {
$url = "http://".$url;
}
// make sure it has the www on it
if(substr($url, 7, 4) != "www.") {
$url = str_replace('http://', 'http://www.', $url);
}
// extract the youtube ID from the url
if(substr($url, 0, 31) == "http://www.youtube.com/watch?v=") {
$id = substr($url, 31, 11);
}
return $id;
}
// will accept a youtube video ID
// returns title, description, thumbnail
function getVideoDetails($id)
{
// create an array to return
$videoDetails = Array();
// get the xml data from youtube
$url = "http://gdata.youtube.com/feeds/api/videos/".$id;
$xml = simplexml_load_file($url);
// load up the array
$videoDetails['title'] = $xml->title[0];
$videoDetails['description'] = $sxml->content[0];
$videoDetails['thumbnail'] = "http://i.ytimg.com/vi/".$id."/2.jpg";
return $videoDetails;
}
}
?>
That's it - again, it's a pretty simple class, but it does a nice clean job of what it's meant to.




