Get Youtube embed code from video URL using PHP

1 min read

In this article, we are going to learn to create Youtube Video Embed code from Youtube Video URL using PHP.

The following source code provides PHP functions to get Youtube video id from video URL and pass it to get the embed code eventually.

 

<?php


function __getYouTubeEmbeddedURL($url) {
    return "https://www.youtube.com/embed/" . __getYouTubeID($url);
}


function __getYouTubeID($url) {
    $queryString = parse_url($url, PHP_URL_QUERY);
    parse_str($queryString, $params);
    if (isset($params['v']) && strlen($params['v']) > 0) {
        return $params['v'];
    } else {
        return "";
    }
}

$url = 'https://www.youtube.com/watch?v=zmxhTXUr9wc';
$embed_code = '<iframe width="560" height="315" src="'.__getYouTubeEmbeddedURL($url).'" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';

echo $embed_code;

 

Recommended For You

About the Author: Ritesh Ghimire