Get YouTube video id form URL using PHP

Mahabubur Rahman
0

Today I will discuss about YouTube video URL and video ID.
First of all what is YouTube video ID?
YouTube video ID is a unique identification number. Every video have a unique identification number. So I will try to show how to get the YouTube unique ID form its URL. For this create a function called getYoutubeIdFromUrl. And write some code as bellow.
if(!function_exists('getYoutubeIdFromUrl')){
                function getYoutubeIdFromUrl($url) {
                    $parts = parse_url($url);
                    if(isset($parts['query'])){
                        parse_str($parts['query'], $qs);
                        if(isset($qs['v'])){
                            return $qs['v'];
                        }else if(isset($qs['vi'])){
                            return $qs['vi'];
                        }
                    }
                    if(isset($parts['path'])){
                        $path = explode('/', trim($parts['path'], '/'));
                        return $path[count($path)-1];
                    }
                    return false;
                }
}
Keep in mind, let's take a look at the function above $parts['query']. When we parse the YouTube URL using php function parse_url() we get a set of array element and the array element 'query' contain the video id with its prefix "v=". 
So after getting the array element query remove the prefix "v=" and you will get the video ID.

Call this function as bellow –
$url="https://www.youtube.com/watch?v=l0J8cKd0LF0";
$output=getYoutubeIdFromUrl($url);
echo $output;
And run the PHP file in your local or online server and you will get the video id. I.E. in this example we will get the id as l0J8cKd0LF0.

Let's take a look at the code, the $url variable contain the YouTube URL and the end of URL v= l0J8cKd0LF0. The right site value is the YouTube video id.

Post a Comment

0Comments
Post a Comment (0)