【问题标题】:Youtube get video title from idYoutube 从 id 获取视频标题
【发布时间】:2017-02-02 13:07:05
【问题描述】:

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

我正在尝试创建一个页面,该页面将显示来自 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 标题的最佳方式。我的代码确实有效,但它也使页面加载非常缓慢。

谢谢

【问题讨论】:

标签: php youtube


【解决方案1】:

这是一种使用 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 才能工作,这可能是共享主机上的问题。

【讨论】:

  • 可惜没有日期信息
【解决方案2】:

您可以使用 Open Graph

Checkout This Link

<?php
    require_once('OpenGraph.php');

    function get_youtube_title($video_id){
        $url = "http://www.youtube.com/watch?v=".$video_id;
        $graph = OpenGraph::fetch($url);
        // You can get title from array
        return $graph->title;
    }

【讨论】:

  • 您好,感谢您的回复!我如何从数组中获取标题?
  • 你可以用这个得到echo $og-&gt;title;
  • 你可以参考你可以轻松理解的链接
  • 似乎没有任何反应
  • 我也在我的项目中实现了它的工作原理。
猜你喜欢
  • 2012-05-22
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 2016-01-11
相关资源
最近更新 更多