MugenFTW
1/16/2017 - 1:05 PM

Gets the duration and title of videos and returns it in an array.

Gets the duration and title of videos and returns it in an array.

<?php 

    class Youtube {
        static $api_key = 'APIKEY';
        static $api_base = 'https://www.googleapis.com/youtube/v3/videos';

        // $vid - video id in youtube
        // returns - video info
        public static function getVideoInfo($vid)
        {
            $params = array(
                'part' => 'contentDetails,snippet',
                'id' => $vid,
                'key' => self::$api_key,
            );

            $result_array = array();

            $api_url = Youtube::$api_base . '?' . http_build_query($params);
            $result = json_decode(@file_get_contents($api_url), true);

            if(empty($result['items'][0]['contentDetails'])) {
                return null;
            } else {
                $count = 0;
                foreach ($result['items'] as $key) {
                    $interval = new DateInterval($key['contentDetails']['duration']);
                    $duration = $interval->h * 3600 + $interval->i * 60 + $interval->s;

                    $result_array[$count]['duration'] = $duration;
                    $result_array[$count]['title'] = $key['snippet']['title'];
                    $count++;
                }
            }

            return $result_array;
        }

    }

    $yt_id = new Youtube;

?>