如何使用PHP检查YouTube上是否存在视频?

时间:2009-09-05 11:13:30

标签: php youtube

如何使用PHP检查YouTube上是否存在视频?

13 个答案:

答案 0 :(得分:38)

使用Youtube的API 怎么样?
毕竟,这意味着要使用一些官方,这不太可能改变,而不是解析一些HTML页面。

有关详细信息: YouTube APIs and Tools - Developer's Guide: PHP

Retrieving a specific video entry似乎非常有趣:如果你向这样的网址发送请求:

http://gdata.youtube.com/feeds/api/videos/videoID

(用视频ID替换“videoID”,当然 - 在你的例子中为“GeppLPQtihA”),如果视频有效,你会得到一些ATOM提要;和“无效的身份证明”,如果它不是


并且,我坚持认为:这样,您依赖于文档化的API ,而不是今天存在的某种行为,但不能保证。

答案 1 :(得分:31)

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 :(
}

答案 2 :(得分:4)

使用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

答案 3 :(得分:1)

您应该请求此网址

https://www.googleapis.com/youtube/v3/videos?id={the_id_of_the_video}&key={your_api_key}&part=status

之后,您将收到包含uploadStatus字段

的响应json
{
    etag = "\"I_8xdZu766_FSaexEaDXTIfEWc0/8QgL7Pcv5G8OwpNyKYJa8PaQTc0\"";
    items =     (
                {
            ...
            status =             {
                embeddable = 1;
                license = youtube;
                privacyStatus = public;
                publicStatsViewable = 1;
                uploadStatus = processed;
            };
        }
    );
    ...
}

uploadStatus

有5种可能值
  

已删除,失败,已处理,已拒绝,已上传

对于uploadStatus = processeduploaded =>您的YouTube视频可用

答案 4 :(得分:1)

在github上找到了以下解决方案: Check if youtube video exists

易于使用:

$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";
}

工作正常。

答案 5 :(得分:0)

您想要验证youtube网址是否是真实YouTube视频的网址?这很难,您可以使用正则表达式,但请记住,有很多有效的方法来表达youtube网址:

视频代码也可以包含字母数字字符,下划线,字符(不知道它们叫什么)以及可能更多。

答案 6 :(得分:0)

另一种(低效率)方式是使用cURL获取所谓视频页面的HTML并运行一些正则表达式来验证它是否是一个实际的视频页面。

答案 7 :(得分:0)

http://www.youtube.com/watch?v=bQVoAWSP7k4  
http://www.youtube.com/watch?v=bQVoAWSP7k4&feature=popular  
http://www.youtube.com/watch?v=McNqjYiFmyQ&feature=related&bhablah  
http://youtube.com/watch?v=bQVoAWSP7k4
var matches = $('#videoUrl').val().match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches) {
    alert('valid');
} else {
    alert('Invalid');
}

答案 8 :(得分:0)

For Each mySrs In ActiveChart.SeriesCollection              'change this function so every series after series 4 changes ast point
    With mySrs

        nPts = .Points.Count
        mySrs.Points(nPts).ApplyDataLabels _
        Type:=xlDataLabelsShowValue, _
        AutoText:=True, LegendKey:=False
        mySrs.Points(nPts).DataLabel.Text = mySrs.Name
        mySrs.Points(nPts).DataLabel.Orientation = 90
        mySrs.Points(nPts).DataLabel.Font.Bold = True

    End With
Next

链接:

https://github.com/DimitriMikadze/php-helpers

答案 9 :(得分:0)

我使用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;
}

答案 10 :(得分:0)

这是使用HEAD请求方法的快速简便的快速解决方案。

function check_youtube_video_exists($video_url) {

    if (strpos($video_url, 'youtube.com') > 0 || strpos($video_url, 'youtu.be') > 0) {
        $video_url = 'https://www.youtube.com/oembed?url='. $video_url .'&format=json';
    }

    $headers = @get_headers($video_url);

    return (strpos($headers[0], '200') > 0) ? true : false;
}

按以下方式检查您的YouTube URL:

if (check_remote_video_exists('YOUR_YOUTUBE_VIDEO_URL')) {
    // video exists, do stuff
} else {
    // video does not exist, do other stuff
}

答案 11 :(得分:0)

这是不涉及使用youtube api的解决方案,它会在加载网址时检查视频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;
}

希望有帮助

答案 12 :(得分:0)

这是我使用视频ID检查YouTube视频是否存在的解决方案。这是C#代码,但是基本上您可以检查视频的缩略图是否存在,您将获得200或404,这非常方便。

    private async Task<bool> VideoExists(string id)
    {
        var httpClient = new HttpClient();
        var video = await httpClient.GetAsync($"https://img.youtube.com/vi/{id}/0.jpg");
        return video.IsSuccessStatusCode;
    }
相关问题