Jump to content
Sign in to follow this  
MrLeN

Get YouTube Video from HTML Page

Recommended Posts

What is the best way to get the video id after /embed/ in the code below?

ie: The page might contain:

<iframe width="1200" height="675" src="https://www.youtube.com/embed/VIDEO_ID?feature=oembed&wmode=opaque&showinfo=0" style="border: none" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Basically, I want to get the video ID, after /embed/ from the html and make a variable called $video_id

$get_url = "http://www.mywebsite.com/mywebpage.html";
 
$html = file_get_contents($get_url);
 
if ($html contains 'https://www.youtube.com/embed/') {
 $video_id = 'VIDEO_ID'
}

 

Share this post


Link to post
Share on other sites

Here is the code if anyone needs it. I paid a guy on Freelancer :)

<?php
 
/**
 * get the video id from html text
 * @param string $html
 * @param int $idsToReturn
 * @return array|string if the $idsToReturn it's > 1 => array; else string of video id 
 */
function getYoutubeIdFromHtml($html = "", $idsToReturn = 1) {
    $ret = array();
    
    if ($html) {
        $matches=array();
        if(preg_match('#youtube.com/embed/([A-Za-z0-9]+)\??/?.+#', $html, $matches)){
            $ret= array_slice($matches, 1);
        }
    }
 
    if ($idsToReturn > 1) {
        return $ret;
    } else {
        return isset($ret[0]) ? $ret[0] : null;
    }
}
 
/**
 * get the video id from page url
 * @param string $url
 * @param int $idsToReturn
 * @return array|string if the $idsToReturn it's > 1 => array; else string of video id 
 */
function getYouTubeIdFromUrl($url, $idsToReturn = 1) {
    $html = file_get_contents($url);
    return getYoutubeIdFromHtml($html, $idsToReturn);
}
 
 
//Example of usage
$videoId= getYouTubeIdFromUrl('https://www.mywebsite.com/page.html', 1);
echo $videoId;
 
?>

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.