How to Download YouTube Video Using PHP Rest API

This PHP tutorial help to create script to download YouTube video. YouTube is most popular online/offline video streaming tools which used to watch video, Mostly we are watching online video but sometimes we need to download video from YouTube and watched later.

YouTube also providing functionality to watch offline videos .You can click offline save option in youtube video and video will saved in your profile video section.You can watch that video anytime without internet access.

The main benefit of offline video is , You do not consume your internet data packs at the time viewing offline video. PHP is most popular web scripting opensource language.We will create PHP script that download YouTube videos on your local server.

There are some tools in market available that providing functionality to download video from YouTube link, here we will use YouTube video URL that do not have exact location of video. The player has URL-encoded string that has the video’s location.We will use that part and download video..

$vid = $_GET['vid']; //the youtube video ID
$vformat = $_GET['vformat']; //the MIME type of the video. e.g. video/mp4, video/webm, etc.
parse_str(file_get_contents("http://youtube.com/get_video_info?video_id=".$vid),$info); //decode the data
$streams = $info['url_encoded_fmt_stream_map']; //the video's location info
$streams = explode(',',$streams);
foreach($streams as $stream){
parse_str($stream,$data); //decode the stream
if(stripos($data['type'],$vformat) !== false){ //We've found the right stream with the correct format
$video = fopen($data['url'].'&signature='.$data['sig'],'r'); //the video
$file = fopen('video.'.str_replace($vformat,'video/',''),'w');
stream_copy_to_stream($video,$file); //copy it to the file
fclose($video);
fclose($file);
echo 'Youtube Video Download finished! Now check the file.';
break;
}
}
?>

How can use to Download YouTube Video

If You have saved into index.php file then you need to pass two params one is youtube video id and other is format type.The URL will look like this,

http://localhost/index.php?vid=W6VVyMbXHZs&vformat=mp4