Aslam Doctor

Generate YouTube Embed Code from URL using PHP

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 user profile modules, and we need to take youtube video URLs from users, it’s very helpful. So that just by using this URL, we can generate Youtube Embed code. And on the Website front-end, we are able to 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);
	$id=$matches[1];
	$embed_code = '<iframe id="ytplayer" type="text/html" width="'.$width.'" height="'.$height.'"
	src="https://www.youtube.com/embed/'.$id.'?rel=0&showinfo=0&color=white&iv_load_policy=3"
	frameborder="0" allowfullscreen></iframe>';
	return $embed_code;
}

Usage :

echo generate_youtube_url('https://www.youtube.com/watch?v=xQs7nvBfX-0', '700px', '400px');

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

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