Embed a youtube video in your page based on a keyword from rss feed
I spent ages looking around for a simple way to automatically embed a youtube video on a page based on a keyword, and found nothing, so here’s a little script that does it for you.
I found scripts that take the thumbnail from Youtube, but I wanted to actually EMBED a video, not show a thumbnail with a link to Youtube.
In a nutshell, here’s what the script does:
1) Takes a keyword you give it
2) Generates an URL to get the Youtube RSS feed for that keyword
3) Takes the first video from that RSS feed
4) EMBEDS that video in your page, so it can be played right there, in your page.
As with most of the scripts you’ll find here, you need PHP5 installed on the server you’re going to run this script on, as it uses PHP5’s SimpleXML to parse the Youtube RSS feed.
First, the PHP to get the RSS Feed:
<?php
//Give our script a keyword to work with
$keyword=”george bush”;
//Generate a URL for our RSS feed, and download the feed using SimpleXML
$rss = simplexml_load_file(’http://gdata.youtube.com/feeds/base/videos?q=’ .urlencode($keyword). ‘&client=ytapi-youtube-search&v=2′);
//Get the part of the RSS feed which contains the number of the first video, and save it to the variable $id
$id = $rss->entry->id;
//Get rid of some stuff we don’t need
$id = str_replace(”tag:youtube.com,2008:video:”, “”, $id);
?>
And Now the part that actually embeds our video in the page (We’re actually just customising Youtube’s standard embed code here, to embed our video):
<embed src=”http://www.youtube.com/v/<?php echo $id; ?>&hl=en&fs=1&color1=0×5d1719&color2=0xcd311b” type=”application/x-shockwave-flash” allowscriptaccess=”always” allowfullscreen=”true” width=”320″ height=”265″></embed>
See how we’re embedding the $id variable, that’s the Youtube ID of our video.
You can download the script here
