Wednesday, 24 May 2017

How to download youtube video in PHP?

How to download youtube video in PHP?

Question: How to Get the YouTube Video Id?
Suppose we have following YouTube URL:
iHp5veCNPVw is YouTube Id.

Question: How to download YouTube using YouTube video Id?
$vid = 'iHp5veCNPVw'; //the youtube video ID
$vformat = 'video/mp4'; //video/mp4, video/webm, video/mp3 et.
$fileName = 'downloadvideos';//File name, downloadvideos.mp4
parse_str(file_get_contents("" . $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
        $fullFileName = $fileName . '.' . str_replace('video/', '', $vformat);
        $file = fopen($fullFileName, 'w');
        stream_copy_to_stream($video, $file); //copy it to the file
        echo 'Downloaded Path:  ' . __DIR__ . '/' . $fullFileName;
    } else {
        echo "Unable to download this video.";

No comments :

Post a Comment