How do I check if a video exists on YouTube, using PHP?

后端 未结 14 1685
[愿得一人]
[愿得一人] 2020-11-27 06:40

How do I check if a video exists on YouTube, using PHP?

14条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 07:08

    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:

    /**
    * 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;
    }
    

提交回复
热议问题