I'm playing now with the Youtube API and I began a small project (for fun).
The problem Is that I cant find the way to get Title of a video from the Id. (example: ylLzyHk54Z0)
I have looked in the DATA and PLAYER api documentation and I cannot find it.
If someone knows how to开发者_如何学C do this or if someone could help me find the way to do this, please help me.
NOTE: I'm using javascript. It will be a web app.
EDIT: I have got an Idea. Maybe using a Regular expresion to parse out the title from the page title. I'm working on this.
Not entirely possible in javascript since you are trying to get a document from a different domain. If you are happy to throw in a bit of php try this. Tested ok:
<?
$vidID = $_POST['vidID'];
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>
<html>
<head>
<title>Get Video Name</title>
</head>
<body>
<form action="test.php" method="post">
<input type="text" value="ID Here" name="vidID" />
<input type="submit" value="Get Name" />
</form>
<div id="page">URL: [<?= $url ?>]</div>
<div id="title">Title: [<?= $title ?>]</div>
</body>
</html>
This is how you can do it with JavaScript and the V3 YouTube Data API.
var ytApiKey = "...";
var videoId = "ylLzyHk54Z0";
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + videoId + "&key=" + ytApiKey, function(data) {
alert(data.items[0].snippet.title);
});
You can use a JSON request to: http://gdata.youtube.com/feeds/api/videos/ylLzyHk54Z0?v=2&alt=jsonc
Call http://gdata.youtube.com/feeds/api/videos/ylLzyHk54Z0
.
In this XML file, read the value of the <title>
tag.
YouTube Api Documentation
This answer is accurate as of December 2015.
To get the video title from an YouTube video id, you will have to construct the following URL, using YouTube Data API (you are required to use an API key, otherwise the request will fail):
https://www.googleapis.com/youtube/v3/videos?part=snippet&id={YOUTUBE_VIDEO_ID}&fields=items(id%2Csnippet)&key={YOUR_API_KEY}
Do a GET request and you will get a JSON response similar to the chunk below. For the title, it exists in the snippet/title
key.
{
"items":[
{
"id":"Jglv0A0qLI8",
"snippet":{
"publishedAt":"2014-06-30T03:42:20.000Z",
"channelId":"UCdTU5vd37FlTZ-xoB0xzRDA",
"title":"AIA Malaysia - A-Plus Venus Plan - Comprehensive Female Protection and Insurance Plan",
"description":"A comprehensive female protection plan for the modern women\n\nFor more information visit: http://www.aia.com.my/en/individuals/products-and-services/health/a-plus-venus-a-plus-venus-extra.html\n\nFor more products, visit AIA Malaysia's Products and Services playlist:\nhttps://www.youtube.com/playlist?list=PLSrgVT3aQ1fZ3SCe-dEVnFJDApBYkqolP\n\nFor more videos. subscribe to AIA Malaysia's YouTube channel:\nhttps://www.youtube.com/channel/UCdTU5vd37FlTZ-xoB0xzRDA",
"thumbnails":{
"default":{
"url":"https://i.ytimg.com/vi/Jglv0A0qLI8/default.jpg",
"width":120,
"height":90
},
"medium":{
"url":"https://i.ytimg.com/vi/Jglv0A0qLI8/mqdefault.jpg",
"width":320,
"height":180
},
"high":{
"url":"https://i.ytimg.com/vi/Jglv0A0qLI8/hqdefault.jpg",
"width":480,
"height":360
},
"standard":{
"url":"https://i.ytimg.com/vi/Jglv0A0qLI8/sddefault.jpg",
"width":640,
"height":480
},
"maxres":{
"url":"https://i.ytimg.com/vi/Jglv0A0qLI8/maxresdefault.jpg",
"width":1280,
"height":720
}
},
"channelTitle":"AIA Malaysia",
"tags":[
"aia",
"aia malaysia",
"a-plus venus",
"female health insurance",
"female life insurance",
"female insurance",
"female medical insurance"
],
"categoryId":"27",
"liveBroadcastContent":"none",
"localized":{
"title":"AIA Malaysia - A-Plus Venus Plan - Comprehensive Female Protection and Insurance Plan",
"description":"A comprehensive female protection plan for the modern women\n\nFor more information visit: http://www.aia.com.my/en/individuals/products-and-services/health/a-plus-venus-a-plus-venus-extra.html\n\nFor more products, visit AIA Malaysia's Products and Services playlist:\nhttps://www.youtube.com/playlist?list=PLSrgVT3aQ1fZ3SCe-dEVnFJDApBYkqolP\n\nFor more videos. subscribe to AIA Malaysia's YouTube channel:\nhttps://www.youtube.com/channel/UCdTU5vd37FlTZ-xoB0xzRDA"
}
}
}
]
}
For more information, visit the API documentation page.
The video title is in the API and reachable in JavaScript using dot notation:
the_name_of_your_video_object.A.videoData.title
The answers of Robert Sim and cbaigorri were the best, that's the correct way to do it at this time with JS, do GET request to:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id={YOUTUBE_VIDEO_ID}&fields=items(id,snippet)&key={YOUR_API_KEY}
A little specification about this: You can use comma separated youtube video IDs to get multiple videos info in one request.
To get 1 video, replace {YOUTUBE_VIDEO_ID}
with video ID (ex: 123456
)
To get more videos in one request, replace {YOUTUBE_VIDEO_ID}
with comma separated IDs (ex: 123456,234567,345678,456789
)
This will count as a single request in the Quotas, this way you can get a lot of video details with only 1 quota/request cost.
Instead of using http://gdata.youtube.com/feeds/api/videos/....
If you have the video loaded, you can use the player object's getVideoData() method to retrieve information on the video, including the title. It will return a object which contains: video_id, author, title.
Using PHP
<?php
echo explode(' - YouTube',explode('</title>',explode('<title>',file_get_contents("https://www.youtube.com/watch?v=$youtube_id"))[1])[0])[0];
?>
I wrote a function to get the title & author of a Youtube video given an id. The function loads a Youtube video in an iframe, then adds a message listener for when Youtube emits its initial message. This initial message contains the video data. It then removes the iframe and message listener from the page.
import { Observable } from 'rxjs';
function getVideoData$(ytId){
return new Observable((observer) => {
let embed = document.createElement('iframe');
embed.setAttribute('src', `https://www.youtube.com/embed/${ytId}?enablejsapi=1&widgetid=99`);
embed.cssText = "position: absolute; display: hidden";
embed.onload = function() {
var message = JSON.stringify({ event: 'listening', id: 99, channel: 'widget' });
embed.contentWindow.postMessage(message, 'https://www.youtube.com');
}
function parseData(e) {
const {event, id, info} = JSON.parse(e.data)
// console.log(JSON.parse(e.data))
if (event == 'initialDelivery' && id == 99) observer.next(info.videoData)
}
document.body.appendChild(embed); // load iframe
window.addEventListener("message", parseData) // add Api listener for initialDelivery
return function cleanup(){
window.removeEventListener("message", parseData)
document.body.removeChild(embed)
}
});
}
I chose to return an observable because the video has to be retrieved async from yt's servers and is then sent back to the iframe and then to a message handler we setup. A promise could be used here instead, but I found that the promise would resolve multiple times, before the message listener gets removed. So I used rxjs to only get the first value. Here is how I use this function.
import { firstValueFrom } from 'rxjs';
getVideoDataFromUrl('https://www.youtube.com/watch?v=3vBwRfQbXkg')
async function getVideoDataFromUrl (url){
const videoId = parseYoutubeUrl(url)
if (!videoId) return false
let videoData = await firstValueFrom(getVideoData$(videoId)) // await video data
console.log({videoData})
}
function parseYoutubeUrl(url) {
var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
let urlMatch = url.match(p)
if(urlMatch) return urlMatch[1];
return false;
}
My solution is:
$xmlInfoVideo = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos/".$videoId."?v=2&fields=title");
foreach($xmlInfoVideo->children() as $title) { $videoTitle = strtoupper((string) $title); }
This get the title of the video.
精彩评论