Monday, February 15, 2016

Get YouTube video id form URL using PHP

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.
                function getYoutubeIdFromUrl($url) {
                    $parts = parse_url($url);
                        parse_str($parts['query'], $qs);
                            return $qs['v'];
                        }else if(isset($qs['vi'])){
                            return $qs['vi'];
                        $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 –
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


Copyright @ 2014 Tech Tutorial .