Get IMDB ID (tt number) from movie title
Sunday, March 07th, 2010 | Author:

I searched on the internet if there is a way to get the IMDB movie ID from movie’s title. As you know the Internet Movie Database has data about every movie on the Earth ever made. Every movie has it’s own ID number which begins with letters tt followed by 7 numbers. The exact URL of a movie looks something like http://www.imdb.com/title/tt2345678/.

The IMDB has some RSS channels but nothing about that. Of course, you can use their search, but what if you need this function in your php script? Imagine parsing some TV guide RSS channel… wouldn’t it be nice to create the IMDB link on every movie you could watch that day?

Here is my class:

class IMDBtt{

	function tt($title){
		$t = urlencode($title);
		$content = $this->getSite('http://www.imdb.com/find?s=tt&q=' . $t);
		$content = substr($content, strpos($content, 'div id="main"'));
		preg_match('/tt[0-9]{7}/',$content,$matches);
		return reset($matches);
	}

	private function getSite($url){
		$ch = curl_init($url);

		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
		curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($ch,CURLOPT_MAXREDIRS,1);

		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}

}

Usage:

$IMDB = new IMDBtt();
$tt = $IMDB->tt('Avatar');
//returns tt0499549

You can create your <a> link like this:

<a href="http://www.imdb.com/title/<?=$tt;?>">Avatar</a>

There is not much more to say about that. Maybe just a little note: if IMDB finds only one match for a movie title, it immediately redirects to it’s site. Therefore I had to use options:

curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_MAXREDIRS,1);

to follow redirect (only once).

If you are working on your localhost you could get error: Call to undefined function curl_init()

  1. Open C:\xampp\apache\bin\php.ini
  2. Remove the semi-colon in front of this line: extension=php_curl.dll
  3. Restart Apache

Demo here.

Category: Web development  | Tags: ,