Jump to content

Get YouTube Video from HTML Page


Go to solution Solved by 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 post
Share on other sites
  • Solution
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 post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.