Download youtube videos using PEAR

PEAR have rich library to access web based resources easily…

<?php

$sv = new SVTube();
$sv->download(“D7cm-yu-CP0”, “svnlabs.flv”)

?>

Class: SVTube.php
——————————

<?php

require_once ‘HTTP/Client.php’;
require_once ‘HTTP/Request.php’;

class SVTube {

var $req;
var $debug = false;
var $auth = false;

function download ($video_id, $video_filename) {
$url = “https://www.youtube.com/watch?v=”.$video_id;
$this->req =& new HTTP_Request($url);
$response = $this->req->sendRequest();

if (PEAR::isError($response)) {
echo $response->getMessage().”\n”;
} else {
$page = $this->req->getResponseBody();

preg_match(‘/\&t=([^”]*)”/si’, $page, $match);

$html=html_entity_decode(urldecode(str_replace(‘\x’, ‘%’, $match[1])),ENT_QUOTES, “UTF-8”);

$echo = explode(“&”, $html);

$url = “https://www.youtube.com/get_video?el=detailpage&t=”.$echo[0].”&fmt=5&asv=3&video_id=”.$video_id;

if ($this->debug)
return $url.”\n”;

$req =& new HTTP_Request($url,array (“allowRedirects”=>true, “maxRedirects”=> 99));
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader(“User-Agent”,”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)”);
$response = $req->sendRequest();

$req->getResponseBody();

if (PEAR::isError($response)) {
//echo $response->getMessage().”\n”;
return “Error: Failed to open video file on YouTube\n”;
} else {
if ($o = fopen ($video_filename, “w”)) {
fwrite($o,$req->getResponseBody());
fclose ($o);
return “Download complete! File: “.$video_filename.”\n”;
} else {
return “Error: Failed to open video-file\n”;
}
}

}
}

}
?>