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 = '';
//extract the ID
//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="//'.$id.'" frameborder="0" allowfullscreen></iframe>';