An important feature of each movie site is trailers, so it is for sharemovi.es! And where should we look for trailers? YouTube! But how can we program to get the corresponding trailer video when inputting the movie title? Use gData!

 

First of all there is a complete YouTube API available, but my solution doesn't require much if any of it. It really comes down to getting the right feed details and parse the XML:

1. First make a query to the gData API (a REST-inspired technology for reading, writing, and modifying information on the web - see also this video: it has been around for quite some time!)

$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q='
  .$q.'&start-index=1&max-results=1';

$q is the movie string to query. the+movie+name+'trailer' works best for me. And we want just the first hit to appear in the feed.

2. Read the feed into a SimpleXML object

$sxml = simplexml_load_file($feedURL);
// and iterate over entries in feed
foreach ($sxml->entry as $entry) {
   // get nodes in media: namespace for media information
   $media = $entry->children('http://search.yahoo.com/mrss/');
   // get video player URL
   $attrs = $media->group->player->attributes();
   $trailer = $attrs['url'];
}

(I found a much more detailed example on the IBM site, but this bit will do for what I want to show ..)

3. Some final tweaking: to embed the gathered URL in a html <object> we need to swap 'watch?v=' with 'v/'. Luckily I played with YouTube URLs before because this is not very obvious.

$trailer = str_replace('watch?v=','v/',$trailer);

.. and we embed the result in the standard embed code YouTube provides to us

<object width="640" height="385"><param name="movie"
value="<?php echo $trailer ;?>?fs=1&amp;hl=en_US"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="<?php echo $trailer ;?>?fs=1&amp;hl=en_US" type="application/x-shockwave-flash"
allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>
</object>

You can see the result on sharemovi.es.

 

I use the jQuery Boxy plugin to present the output as a nice Facebook-like overlay:

A. Click on "View trailer"

B. Overlay with the result of the trailer script that found "The Ghost Writer"'s trailer on YouTube:

Update (09.08.2011)

Some readers requested the source. I put it on Github. Let me know where you roll it out :)


 

Update 20/11/2015:

Gdata is gone, I fixed it by using themoviedb API, see here.


Bob Belderbos

Software Developer, Pythonista, Data Geek, Student of Life. About me