从youtube获取视频链接 [英] Get a video link from youtube

查看:57
本文介绍了从youtube获取视频链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个应用程序中,我需要显示一个 YouTube 视频.如果用户提交视频,那么我必须检查该视频是否在 YouTube 中存在.如果可以,那么我必须将视频 ID 保存在我的数据库中并在网页中生成视频.

In one of my application I need to show a YouTube video. If user submits a video then I have to check if that video is alive in YouTube. If OK then I have to save the video id in my database and generate video in web page.

有什么方法可以验证 YouTube 视频吗?

Is there any method for validating YouTube video ?

推荐答案

使用此类来提取和验证 youtube 视频.这适用于 YT 网址,如/embed/、/v/、 ?v=/、 youtu.be

Use this class to extract and validate youtube video. This works for YT urls like /embed/ , /v/ , ?v= /, youtu.be

class Youtube {
///// Put together by Sugato


////////// $video_id is the youtube video ID /////////////////////////
public $video_id = null;

///////// the Constructer ////////////////////////////////////////
public function __construct($url)
{
    if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
          $this->video_id = $id[1];
    } else {   
          $this->video_id  = NULL;
    }

}
/////////// validates if a youtube video actually exists //////////////
function validate()
{
    if(empty($this->video_id))
    {
        return false;
    }
    else {
            $curl = curl_init("http://gdata.youtube.com/feeds/api/videos/" . $this->video_id);
            curl_setopt($curl, CURLOPT_HEADER, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_exec($curl);
            $request = curl_getinfo($curl);
            curl_close($curl);

            $result = explode(";", $request["content_type"]);

            if($result[0] == "application/atom+xml")
            {

                return true;

            } else {

                return false;

            }
    }
}


}

像这样调用类

  $yt = new Youtube($your_video_link_here);
    $exist  = $yt->validate();

    if($exist) 
    {
       echo "Yaaaayyyyyy!";
    } else
    {
       echo "nAAAAyyyy!!!";
    }

这篇关于从youtube获取视频链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆