Tuesday, April 17, 2007

Download youtube videos with a PHP script

Youtube is a great video archive but it doesn't allow users to download videos. Today I've found a simple script that allows to get all flash videos uploaded by a specific youtube user where the title matches a pattern (regexp compatible). You should run it in the shell or rewrite it for you needs. There is the script:

<?php

ini_set('memory_limit', '1024M');
if(!($argv[1] && $argv[2]))
die("Usage: php youtube-user.php \n");

$user = $argv[1];
$pattern = $argv[2];

echo "Attempting to download all videos by user $user matching the pattern '$pattern'\n";

$file = file_get_contents('http://www.youtube.com/profile?user='.$user);
preg_match_all('!(watch\?v=[A-Za-z0-9]{11}).*?'.$pattern.'!', $file, $matches, PREG_PATTERN_ORDER);
$titles = array_unique($matches[1]);

foreach($titles as $title)
{
$page = file_get_contents('http://www.youtube.com/'.$title);
preg_match('!<title>(.*?)>/title>!', $page, $matches);
echo 'Downloading '.$matches[1]."\n";

preg_match('!video_id=.*&t=[^\"&]*!', $page, $matches);
$video = 'http://youtube.com/get_video?'.$matches[0];

$video_file = file_get_contents($video);
$parts = explode('=', $title);
file_put_contents($parts[1].'.flv', $video_file);
}

?>

0 comments: