如何使用 PHP 检查 YouTube 上是否存在视频?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1383073/
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
How do I check if a video exists on YouTube, using PHP?
提问by Fero
How do I check if a video exists on YouTube, using PHP?
如何使用 PHP 检查 YouTube 上是否存在视频?
回答by Pascal MARTIN
What about using Youtube's API?
After all, that would mean using some official, which is less likely to change than going with parsing some HTML page.
怎么样使用YouTube的API?
毕竟,这意味着使用一些官方的,这比解析一些 HTML 页面更不可能改变。
For more information: YouTube APIs and Tools - Developer's Guide: PHP
有关更多信息:YouTube API 和工具 - 开发人员指南:PHP
The Retrieving a specific video entryseems quite interesting: if you send a request to an URL like this one:
该检索特定的视频条目似乎很有趣:如果你发送到像这样的一个URL的请求:
http://gdata.youtube.com/feeds/api/videos/videoID
(replacing "videoID" by the ID of the video, of course – "GeppLPQtihA" in your example), you'll get some ATOM feed if the video is valid; and "Invalid id" if it's not
(当然,用视频的 ID 替换“videoID”——在你的例子中是“GeppLPQtihA”),如果视频有效,你会得到一些 ATOM 提要;如果不是,则为“无效 ID”
And, I insist: this way, you rely on a documented API, and not on some kind of behavior that exists today, but is not guaranteed.
而且,我坚持:这样,您就依赖于文档化的 API,而不是依赖于今天存在但不能保证的某种行为。
回答by Giacomo Tecya Pigani
Youtube has support for the oEmbedformat.
Compared to the xml responsed provided by Pascal MARTIN, mine has only to download 600 bytes against 3800 bytes, making it faster and less bandwidth cosuming (only 1/6 of the size).
Youtube 支持oEmbed格式。
与 Pascal MARTIN 提供的 xml 响应相比,我的只需下载 600 字节对 3800 字节,使其速度更快,占用的带宽更少(只有大小的 1/6)。
function yt_exists($videoID) {
$theURL = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$videoID&format=json";
$headers = get_headers($theURL);
return (substr($headers[0], 9, 3) !== "404");
}
$id = 'yyDUC1LUXSU'; //Video id goes here
if (yt_exists($id)) {
// Yep, video is still up and running :)
} else {
// These aren't the droids you're looking for :(
}
回答by gnud
Request the URLs with the HEAD method, like so:
使用 HEAD 方法请求 URL,如下所示:
HEAD /watch?v=p72I7g-RXpg HTTP/1.1
Host: www.youtube.com
HTTP/1.1 200 OK
[SNIP]
HEAD /watch?v=p72I7g-BOGUS HTTP/1.1
Host: www.youtube.com
HTTP/1.1 303 See Other
[SNIP]
Location: http://www.youtube.com/index?ytsession=pXHSDn5Mgc78t2_s7AwyMvu_Tvxn6szTJFAbsYz8KifV-OP20gt7FShXtE4gNYS9Cb7Eh55SgoeFznYK616MmFrT3Cecfu8BcNJ7cs8B6YPddHQSQFT7fSIXFHd5FmQBk299p9_YFCrEBBwTgtYhzKL-jYKPp2zZaACNnDkeZxCr9JEoNEDXyqLvgbB1w8zgOjJacI4iIS6_QvIdmdmLXz7EhBSl92O-qHOG9Rf1HNux_xrcB_xCAz3P3_KbryeQk_9JSRFgCWWgfwWMM3SjrE74-vkSDm5jVRE3ZlUI6bHLgVb7rcIPcg
回答by Phan Van Linh
You should request to this URL
你应该请求这个 URL
https://www.googleapis.com/youtube/v3/videos?id={the_id_of_the_video}&key={your_api_key}&part=status
After that, you will receive the response json that contains uploadStatusfield
之后,您将收到包含uploadStatus字段的响应json
{
etag = "\"I_8xdZu766_FSaexEaDXTIfEWc0/8QgL7Pcv5G8OwpNyKYJa8PaQTc0\"";
items = (
{
...
status = {
embeddable = 1;
license = youtube;
privacyStatus = public;
publicStatsViewable = 1;
uploadStatus = processed;
};
}
);
...
}
And there are 5 possible value for uploadStatus
并且有 5 个可能的值 uploadStatus
deleted, failed, processed, rejected, uploaded
删除、失败、处理、拒绝、上传
For uploadStatus= processedor uploaded=> your youtube video is available
对于uploadStatus=processed或uploaded=> 您的 YouTube 视频可用
回答by Andras Barth
Found this solution on github: Check if youtube video exists
在 github 上找到了这个解决方案: 检查 youtube 视频是否存在
Easy to use:
便于使用:
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=nonexistingid');
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
}
Working fine.
工作正常。
回答by paris93
Here is a solution that doesn't involve using youtube api, it checks if the video id exists when the url is loaded
这是一个不涉及使用 youtube api 的解决方案,它会在加载 url 时检查视频 ID 是否存在
function checkYoutubeUrlIsValid($url) {
$buffer = file_get_contents($url);
$matches = [];
preg_match('#[a-zA-Z0-9_-]{11}$#', $url, $matches);
return strpos($buffer, $matches[0]) !== false;
}
Hope that helps
希望有帮助
回答by von v.
As commented by @dbro, the answer by Pascal MARTINwas an acceptable answer at that time. However, since the API had moved forward, fixed and improved, a new solution that works is the following. Please take note that this is based on the technique provided by @Pascal and I quote:
正如@dbro 所评论的那样,Pascal MARTIN的回答在当时是可以接受的。然而,由于 API 已经向前推进、修复和改进,一个有效的新解决方案如下。请注意,这是基于@Pascal 提供的技术,我引用:
...if you send a request to an URL like this one
http://gdata.youtube.com/feeds/api/videos/videoID
(Replacing "videoID" by the idea of the video, of course -- "GeppLPQtihA" in your example)
You'll get some ATOM feed (**STOP HERE**)
The new URL to use and this is for V3of the API is https://www.googleapis.com/youtube/v3/videos?id={the_id_of_the_video}&key={your_api_key}&part={parts}
要使用的新 URL 是用于API 的V3的https://www.googleapis.com/youtube/v3/videos?id={the_id_of_the_video}&key={your_api_key}&part={parts}
WHERE
在哪里
{the_id_of_the_video}you should know what this is{your_api_key}is your app's key that can be found in your Developer Console{parts}a comma-separated list, check herefor valid values
Now for the Result
现在是结果
If the Video Id is VALIDyou will get data in the itemsfield that includes the Id of the video and the information you queried through the partsparameter.
如果Video Id 为 VALID,您将在items字段中获得数据,其中包括视频的 Id 和您通过part参数查询的信息。
If the Video Id is NOT VALIDthen you will get an empty items.
如果视频 ID 无效,那么您将获得一个空项目。
Supplying a wrong keygives you an ERROR 400(an error object).
提供错误的密钥会给你一个ERROR 400(一个错误对象)。
回答by Dimi Mikadze
/**
* Check youtube url, check video exists or not,
*
* @param $url full youtube video url
*
* @return string - yotube video id
*/
public static function checkYoutube($url)
{
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match))
{
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $match[1]);
if (strpos($headers[0], '200'))
{
return $match[1];
}
return false;
}
return false;
}
link:
关联:
回答by Nadir Latif
I used the YouTube API for checking if a video exists on You Tube. I downloaded the Google API Client Library for PHP. I used the following function:
我使用 YouTube API 来检查 You Tube 上是否存在视频。我下载了用于 PHP 的 Google API 客户端库。我使用了以下功能:
/**
* Used to check if the given movie is availabe on youtube
*
* It uses youtube api and checks if given movie is available on youtube
* If a movie is not available then it returns false
*
* @param string $youtube_video_url the youtube movie url
*
* @return boolean $is_available indicates if the given video is available on youtube
*/
private function IsMovieAvailable($youtube_video_url)
{
/** The autoload.php file is included */
include_once("autoload.php");
/** Is available is set to false */
$is_available = false;
/** The youtube video id is extracted */
$video_id = str_replace("https://www.youtube.com/watch?v=", "", $youtube_video_url);
$DEVELOPER_KEY = $google_api_key;
$client = new \Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new \Google_Service_YouTube($client);
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->videos->listVideos('status', array('id' => $video_id));
/** Each item in the search results is checked */
foreach ($searchResponse['items'] as $video) {
/** If the video id matches the given id then function returns true */
if ($video['id'] == $video_id) {
$is_available = true;
break;
}
}
return $is_available;
}
回答by Pim Jager
You want to validate if a youtube url is an url to a real youtube video? This is quite hard, you could use regular expressions, but keep in mind that there are loads of valid ways to express a youtube url:
您想验证 youtube 网址是否是真实 youtube 视频的网址?这很难,您可以使用正则表达式,但请记住,有很多有效的方法可以表达 youtube 网址:
- http://www.youtube.com/watch?v=p72I7g-RXpg
- http://www.youtube.com/watch?asv=76621-2&v=p72I7g-RXpg
- http://www.youtube.com/v/RdPxlTX27Fk
- etc.
- http://www.youtube.com/watch?v=p72I7g-RXpg
- http://www.youtube.com/watch?asv=76621-2&v=p72I7g-RXpg
- http://www.youtube.com/v/RdPxlTX27Fk
- 等等。
Also the video code can contain alphanumeric characters, underscores, -characters (dunno what they are called) and possibly more.
此外,视频代码可以包含字母数字字符、下划线、-字符(不知道它们叫什么)等等。

