How To Convert YouTube URL To Embed Code in PHP
Every YouTube contains a unique key or ID. We’ll grab this key and use it to generate our own embed code.
//store the URL into a variable $youtube_url = 'https://www.youtube.com/watch?v=eLl7Y29eC7o'; //extract the ID preg_match( '/[\?\&]v=([^\?\&]+)/', $url, $matches ); //the ID of the YouTube URL: eLl7Y29eC7o $youtube_id = $matches[1]; //set a custom width and height $width = '640'; $height = '360'; //echo the embed code. You can even wrap it in a class echo '<iframe width="' .$width. '" height="'.$height.'" src="//www.youtube.com/embed/'.$id.'" frameborder="0" allowfullscreen></iframe>';