如何检查youtube上是否存在视频ID

时间:2015-09-29 23:53:18

标签: php youtube google-api

我要做的是检查用户输入的视频是否真的存在,我已经搜索了很多并找到了这个:ReRetrieving_Video_Entry,但看起来它已经弃用了,所以怎么可能使用Google APIs Client Library for PHP检查视频是否存在?

2 个答案:

答案 0 :(得分:2)

我已经使用这种技术修复了它,它不需要使用API

   $headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $key);

    if(is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false){
        // video exists

    } else {
        // video does not exist
        echo json_encode(array('Error','There is no video with that Id!'));
    }

答案 1 :(得分:1)

这是我正在使用的,它运作得很好。 Youtube API v2. Deprecated

$video = "cK3N2DC3Fds";            
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/'.$video);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$content = curl_exec($ch);
curl_close($ch);
if ($content && $content !== "Invalid id" && $content !== "No longer available") {           
    $xml   = new SimpleXMLElement($content);
}else {
 //Doesn't exist
}

您可以使用YouTube Data API (v3)检查视频是否存在。从here下载/克隆API。

这是我制作的一个脚本,用于检查视频是否存在给定的YouTube视频ID。

require_once dirname(__FILE__).'/../google-api/src/Google/autoload.php'; // or wherever autoload.php is located

    $DEVELOPER_KEY = 'yourkey';

    $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);

    $video = "cK3N2DC3Fds"; //Youtube video ID
    $searchResponse = $youtube->search->listSearch('id', array(
      'q' => $video, //The search query, can be a name or anything,
      'maxResults' => 1, //Query result limit
      "type" => "video"
    ));

    $exists = false;
    foreach ($searchResponse['items'] as $searchResult) {
        //if type is video, this will always be "youtuve#video"
        if($searchResult['id']['kind'] == "youtube#video"){ 
            if($video ==  $searchResult['id']['videoId']){
                $exists = true;
            }
        }
     }

     if(!$exists){
        echo "video not found";
     }else echo "video found";