Jump to content

Get YouTube Video from HTML Page


Guest MrLeN

Recommended Posts

Guest MrLeN
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'
}

 

Link to comment
Share on other sites

Guest MrLeN

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;
 
?>
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

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.