如何使用 YouTube API 获取视频时长? [英] How to get video duration using YouTube API?
本文介绍了如何使用 YouTube API 获取视频时长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取 Youtube 视频的时长.这是我试过的代码:
I want to get the duration of a Youtube video. Here's the code I tried:
$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;
请检查 XML 文件.我得到了这个视频的标题.我想从
获取持续时间.
Please check the XML file. I got the title of this video. I want to get duration from <yt:duration seconds='29'/>
.
如何获取这个
标签的seconds
属性?
How to get the seconds
attribute this <yt>
tag?
推荐答案
由于 YouTube v2 API 即将弃用,这里有一个更新的解决方案.
- 首先在此处 克隆 Google API PHP 客户端
- 接下来,您需要通过创建一个新项目向 Google 此处注册一个应用程序,在API 和身份验证 → API"部分下打开 YouTube 数据 API,以及
- 在API 和身份验证 → 凭据"下创建一个新的 OAuth 客户端 ID,并将完整路径添加到您的重定向 URI 列表中.(即http://example.com/get_youtube_duration.php)
- 使用此代码(改编自this 示例代码),同时确保使用您自己的值填写 $OAUTH2_CLIENT_ID 和 $OAUTH2_CLIENT_SECRET 变量第 3 步.
- 硬编码 $videoId 变量的值或使用 video_id 获取参数设置它(即 http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
- 访问您的脚本,点击链接以授权应用程序并使用您的 Google 帐户获取令牌,该令牌会将您重定向回您的代码并显示持续时间.
- Start by cloning the Google API PHP Client here
- Next, you'll want to register an application with Google here by creating a new Project, turning on the YouTube Data API under the "APIs and auth → API" section, and
- 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)
- Use this code (which was adapted from this sample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
- 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)
- 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.
这是您的输出:
Video Duration
0 mins
29 secs
一些额外的资源:https://developers.google.com/youtube/v3/docs/视频#contentDetails.durationhttps://developers.google.com/youtube/v3/docs/videos/列表
基于提要中只有一个持续时间元素的假设,这对我有用.
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 />";
输出:
TITLE: Introducing iTime
Duration: 29
这篇关于如何使用 YouTube API 获取视频时长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文