Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //==> usage
- // youtube data retrieving
- $youtube = new YouTubeAPI();
- $youtube->setAPIKey($APIKey);
- // all videos data
- $videos = $youtube->getLatestUploads("ChannelName");
- /*
- Notice: sorted by date by default, latest on top
- If you want to have the latest on the bottom,
- just reverse the array using the command:
- $videos = array_reverse($videos);
- */
- //==> class
- class YouTubeAPI {
- private $api;
- // API
- public function setAPIKey($api)
- {
- $this->api = $api;
- }
- public function getAPIKey()
- {
- return $this->api;
- }
- // VIDEOS
- public function getLatestUploads($channel)
- {
- $playlistId = $this->getPlaylistUploads($channel);
- return $this->getPlaylistVideos($playlistId);
- }
- public function getPlaylistUploads($username)
- {
- return $this->getRelatedPlaylists($username, "uploads");
- }
- public function getPlaylistVideos($playlistId, $maxResults=30)
- {
- $url = $this->getUrl("playlistItems", array(
- "part" => "snippet",
- "order" => "date",
- "maxResults" => $maxResults,
- "playlistId" => $playlistId,
- ));
- $data = $this->getData($url);
- return $data;
- }
- public function getRelatedPlaylists($username=null, $playlist="uploads")
- {
- // possible values: likes, uploads
- if($username === null) {
- return null;
- }
- $url = $this->getUrl("channels", array(
- "part" => "contentDetails",
- "forUsername" => $username,
- ));
- $data = $this->getData($url);
- $PID = @$data["items"][0]["contentDetails"]["relatedPlaylists"][$playlist];
- if(empty($PID)) {
- $PID = null;
- }
- return $PID;
- }
- // DATA
- private function getUrl($service, $data)
- {
- if(empty($data["key"])) {
- $data["key"] = $this->getAPIKey();
- }
- $query = http_build_query($data);
- $url = sprintf("https://www.googleapis.com/youtube/v3/%s?%s", $service, $query);
- return $url;
- }
- private function getData($url)
- {
- $ch = curl_init();
- curl_setopt_array($ch, array(
- CURLOPT_URL => $url,
- CURLOPT_PORT => 443,
- CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
- CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
- CURLOPT_TIMEOUT => 10,
- CURLOPT_CONNECTTIMEOUT => 5,
- CURLOPT_AUTOREFERER => false,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_USERAGENT => "pkern.at VideoFeedRetriever",
- ));
- $data = curl_exec($ch);
- curl_close($ch);
- $json = json_decode($data, true);
- if(is_array($json)) {
- return $json;
- }else{
- return $data;
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment