Personal Project

Thursday, June 2, 2016

How to get Video Info by using Youtube Datat API ?

Get Started

Youtube Data API has provided an HTTP interface to retrieve plenty of counter numbers to record who has seen or voted for your video. You simply send a GET request shown below to youtube and will get all the information related to your video.

GET Request

https://www.googleapis.com/youtube/v3/videos?id=[VIDEO ID]&key=[ API KEY]&fields=items%28id,snippet%28channelTitle,title,thumbnails%29,statistics%29&part=snippet,contentDetails,statistics

VIDEO ID is a unique key to identify the Video.
API KEY   is the key which you must create a service to use Youtube Data API at Google Developer API Console.

How to implement this feature in PHP ?

Send a GET Request to Youtube

 The function below shows how to send a GET request to Youtube by using Youtube Data  API.
function getYoutubeInfo($videoId, $key)
    {       
        // Get cURL resource
        $curl = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => 'https://www.googleapis.com/youtube/v3/videos?id='.$videoId.'&key='.$key.'&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics',
            CURLOPT_USERAGENT => 'Your Agent Name'
        ));
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
       
        $resp = json_decode($resp, true);
           
        if(!isset($resp['code']))
        {
            if(isset($resp['items']))
            {
                foreach ($resp['items'] as $data)
                {
                    $dataArray = array();
                    $dataArray = $data['snippet'];                                   
                                   
                    $tmpArray = $data['statistics'];
                    //  You can get ViewCount, likeCount, and CommentCount here
                    error_log("### get respond viewCount:" . $tmpArray['viewCount']. " likeCount" . $tmpArray['likeCount']. " commentCount:" .$tmpArray['commentCount']);               
               
                    //  You can get the image url of your video
                    return $dataArray['thumbnails'];

                }
            }
        }   
        // Close request to clear up some resources
        curl_close($curl);
        return;
    }






No comments:

Post a Comment