Generate Youtube Embed Code from URL using PHP

This is just a quick code snippet post on How to generate Youtube Embed Code from URL string PHP. Basically when we are building a user profile modules, and we need to take youtube video URLs from users, its very helpful. So that we just by using this URL, we can generate Youtube Embed code. And on the Website frontend, we are able show the Youtube Video Player in place of just a link.

So below is the Code Snippet.

function generate_youtube_url($url, $width='600px', $height='350px'){
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $url, $matches);
$embed_code = '<iframe id="ytplayer" type="text/html" width="'.$width.'" height="'.$height.'"
frameborder="0" allowfullscreen></iframe>';
return $embed_code;

Usage :

echo generate_youtube_url('', '700px', '400px');

First argument is the Youtube URL, second is the Width of the Video player and third is the Height of the Video Player. Here Video Player Height & Width are optional. If you don’t give it, it will generage default 600×350 size video player.

If you find this useful, please share with others and leave your comments.