How to correctly use oembed to pull thumbs from youtube

隐身守侯 提交于 2019-12-06 01:17:31

I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.

Feel free to ask if you need more help.

<?php

$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video

function getJson($youtube_url){

    $baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
    $url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json

    $json = json_decode(file_get_contents($url)); // gets url and decodes the json

    return $json;

}

$json = getJson($youtube_url);

// from this point on you have all your data placed in variables.

$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};

echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image

Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.

function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
    return false;

if (!empty($parsedUrl['query']))
{
    $query = array();
    parse_str($parsedUrl['query'], $query);
    if (!empty($query['v']))
        return $query['v'];
}

if (strtolower($parsedUrl['host']) == 'youtu.be')
    return trim($parsedUrl['path'], '/');

return false;
}

Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.

<?php
  $vid_id = getVideoId($video_code);
  $json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
  echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">'; 
?>

The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!