Youtube从id获得视频标题

时间:2017-02-02 13:07:05

标签: php youtube

我知道这可能已在某处得到解答,但在查看并查看了大量问题/答案和其他网站后,我无法找到合适的答案。

我正在尝试创建一个页面,该页面将显示来自Youtube的一些视频。它将显示图像和标题。我设法做了这两件事,虽然我的标题有问题。使用我使用的代码,加载速度非常慢。我假设因为加载实际网站只是为了得到标题。

这就是我目前使用的标题。

function get_youtube_id($url){
    parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
    return $my_array_of_vars['v']; 
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;

$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);

$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;

return $title;

}

那么,如何通过id获得youtube标题的最佳方式。我的代码确实有效,但它也使页面加载速度非常慢。

由于

2 个答案:

答案 0 :(得分:5)

这是一种使用PHP而不使用库的简单方法。 YouTube已经允许您以JSON格式检索视频详细信息,因此您只需要一个简单的功能:

   function get_youtube_title($ref) {
      $json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
      $details = json_decode($json, true); //parse the JSON into an array
      return $details['title']; //return the video title
    }

功能参数是视频ID。您还可以添加第二个参数,询问特定的详细信息并更改函数名称,以便您可以从JSON中检索任何您想要的数据。

修改

如果您想从返回的视频详细信息中检索任何信息,可以使用此功能:

function get_youtube_details($ref, $detail) {
    if (!isset($GLOBALS['youtube_details'][$ref])) {
        $json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
        $GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
    }

    return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}

如果您请求有关同一视频的不同详细信息,则返回的JSON数据将存储在$GLOBALS数组中,以防止对file_get_contents进行必要的调用。

此外,allow_url_fopen必须启用php.ini才能file_get_contents工作,这可能是共享主机上的问题。

答案 1 :(得分:0)

  

您可以使用Open Graph

Checkout This Link

col3
2012-01-12 18:09:42
2014-07-01 00:00:01