I was wanting to embed my latest youtube video on my website. What I mean is, I wanted a simple embed script that would always show the latest video I’d uploaded. After discovering that Youtube doesn’t provide a simple way to do this I started googling to see if someone had written a script for it. I had no luck, so I’ve written one.

Taking use of some simple web scraping from the YouTube API, it’ll take the latest video from any Youtuber and embed a player with the what ever size the coder chooses.

It’s written in PHP and is just one function that can be called anywhere on your page. It takes three parameters: the username, the desired video width and the desired video height.

So here’s the first part which I recommend you place at the top of your page, I’ve commented it to help show what’s happening.

Function to embed the latest video from a YouTube Channel.
Parameters: The username of the Youtuber, the desired width of the video, the desired height of the video.
Example call: get_latest_video(‘wormholer693′, ’640′, ’385′);
Author: Andy Barratt
Website: http://www.andybarratt.co.uk

function get_latest_video($username, $width, $height)
        //Set the URL of the search we’re using to get the specified user’s uploads.
        $url = ‘http://gdata.youtube.com/feeds/api/users/’.$username.‘/uploads’;
        //Get the results from the url above and store them in a variable.
        $data = file_get_contents($url);
        //Create a filter to find the url of the first video in the retrieved data.
        $filter = "/<media:content url=’(.+?)’/";
        //Use the preg_match function to run our filter on our data and return scraped text then the filtered text (video url) in an array.
        //store our videoURL in a variable.
        $videoURL = $results[1];
        //if a video was found
                //generate the code required to embed the video.
                $embedCode = ‘<object width="’.$width.‘" height="’.$height.‘"><param name="movie" value="’.$videoURL.‘"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="’.$videoURL.‘" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="’.$width.‘" height="’.$height.‘"></embed></object>’;
                //echo the embed code
                echo $embedCode;
                echo ‘No Video Found.’;

So the above is the actual function and below is how we call it, we just call the function stating the username, width and height of the video and it’ll do the rest. So just place the following bit where ever you want the video to appear in your code.

get_latest_video(‘wormholer693′, ’470′, ’283′);

You can see this code in action on my Videos Page. Feel free to use it, I’d love to know what you think in the comments below.