php 如何使用 YouTube API 获取视频时长?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18920336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:28:45  来源:igfitidea点击:

How to get video duration using YouTube API?

phpxmlapiyoutube-api

提问by Developer

I want to get the duration of a Youtube video. Here's the code I tried:

我想获得 Youtube 视频的持续时间。这是我试过的代码:

$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;

Please check the XML file. I got the title of this video. I want to get duration from <yt:duration seconds='29'/>.

请检查 XML 文件。我得到了这个视频的标题。我想从<yt:duration seconds='29'/>.

How to get the secondsattribute this <yt>tag?

如何获取seconds这个<yt>标签的属性?

回答by Chris Rasco

Due to the upcoming deprecation of the YouTube v2 API, here is an updated solution.

由于即将弃用 YouTube v2 API,这里有一个更新的解决方案。

  1. Start by cloning the Google API PHP Client here
  2. Next, you'll want to register an application with Google hereby creating a new Project, turning on the YouTube Data API under the "APIs and auth → API" section, and
  3. Create a new OAuth Client ID under "APIs and auth → Credentials" and add the full path to your redirect URI list. (i.e. http://example.com/get_youtube_duration.php)
  4. Use thiscode (which was adapted from thissample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
  5. Hardcode a value for the $videoId variable or set it using the video_id get parameter (i.e. http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
  6. Visit your script, click the link to authorize the app and use your google account to get a token, which redirects you back to your code and will display the duration.
  1. 首先在此处克隆 Google API PHP Client
  2. 接下来,您需要通过创建一个新项目,在“API 和身份验证 → API”部分下打开 YouTube 数据 API,在此处向 Google 注册一个应用程序,然后
  3. 在“APIs and auth → Credentials”下创建一个新的 OAuth 客户端 ID,并将完整路径添加到您的重定向 URI 列表。(即http://example.com/get_youtube_duration.php
  4. 使用代码(这是改编自示例代码),而从第3步确保填写$ OAUTH2_CLIENT_ID和$ OAUTH2_CLIENT_SECRET变量与自己的价值观。
  5. 硬编码 $videoId 变量的值或使用 video_id 获取参数(即http://example.com/get_youtube_duration.php?video_id=XXXXXXX)设置它
  6. 访问您的脚本,单击链接以授权应用程序并使用您的 google 帐户获取令牌,该令牌会将您重定向回您的代码并显示持续时间。

Here is your output:

这是您的输出:

Video Duration

0 mins

29 secs

Some additional resources: https://developers.google.com/youtube/v3/docs/videos#contentDetails.durationhttps://developers.google.com/youtube/v3/docs/videos/list

一些其他资源:https: //developers.google.com/youtube/v3/docs/videos#contentDetails.duration https://developers.google.com/youtube/v3/docs/videos/list

The following works for the V2 API only.

以下内容仅适用于 V2 API。

This worked for me based on the assumption that there is only one duration element in the feed.

基于提要中只有一个持续时间元素的假设,这对我有用。

<?php

$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');

print "TITLE: ".$title."<br />";
print "Duration: ".$duration ."<br />";

Output:

输出:

TITLE: Introducing iTime
Duration: 29

回答by Alaa Sadik

Here it is YouTube API V3, with example of getting video duration, but do not forget to create your API key at https://console.developers.google.com/project

这是 YouTube API V3,以获取视频时长为例,但不要忘记在https://console.developers.google.com/project创建您的 API 密钥

     $vidkey = "cHPMH2sa2Q" ; video key for example 
$apikey = "xxxxxxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime) 
{
$VidDuration= $vidTime['contentDetails']['duration'];
}

回答by Amal Murali

A short and simple solution using SimpleXML:

使用 SimpleXML 的简短解决方案:

function getYouTubeVideoDuration($id) {
 $xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/'.$id);
 return strval($xml->xpath('//yt:duration[@seconds]')[0]->attributes()->seconds);
}

回答by Nimrod007

All the prev answers provide the duration in a text format:

所有上一个答案都以文本格式提供持续时间:

This solution will give you the hours / minutes / seconds for you to transform to whatever format you would like:

此解决方案将为您提供小时/分钟/秒以转换为您想要的任何格式:

function getDurationInSeconds($talkId){
   $vidkey = $talkId;
   $apikey = "xxxxx";
   $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
   $VidDuration =json_decode($dur, true);
   foreach ($VidDuration['items'] as $vidTime)
   {
       $VidDuration= $vidTime['contentDetails']['duration'];
   }
   preg_match_all('/(\d+)/', $VidDuration, $parts);
   $hours = intval(floor($parts[0][0]/60) * 60 * 60);
   $minutes = intval($parts[0][0]%60 * 60);
   $seconds = intval($parts[0][1]);
   $totalSec = $hours + $minutes + $seconds; // This is the example in seconds
   return $totalSec;
}

回答by hakiko

Very easy

好简单

function getYoutubeDuration($videoid) {
      $xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
      $result = $xml->xpath('//yt:duration[@seconds]');
      $total_seconds = (int) $result[0]->attributes()->seconds;

      return $total_seconds;
}

//now call this pretty function. As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");

回答by havefun

You can also get the duration in JSON

您还可以在 JSON 中获取持续时间

       $video_id = "<VIDEO_ID>";
       http://gdata.youtube.com/feeds/api/videos/$video_id?v=2&alt=jsonc

Oh! Sorry you can get it by:

哦!抱歉,您可以通过以下方式获得:

$duration = $xml->getElementsByTagName('duration')->item(0)->getAttribute('seconds');