Skip to content

Instantly share code, notes, and snippets.

@amurrell
Created June 2, 2015 21:29
Show Gist options
  • Save amurrell/aebbfaa1c12ff3064723 to your computer and use it in GitHub Desktop.
Save amurrell/aebbfaa1c12ff3064723 to your computer and use it in GitHub Desktop.
YouTubeAPI - V3 - Search by Keyword for Videos
<?php
// Make your key https://console.developers.google.com
define('YOUTUBE_API_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXX');
class YouTubeAPI {
private $keyword="";
private $maxResults = 10;
private $order = "viewCount";
private $query = '';
private $data = '';
public function __construct($keyword, $maxResults = 10, $order = 'viewCount') {
$this->keyword = $keyword;
$this->maxResults = $maxResults;
$this->order = $order;
$this->query = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' . urlencode($keyword) . "&maxResults=$maxResults&order=$order&key=" . YOUTUBE_API_KEY;
$this->getData();
}
private function getData (){
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Content-Type: type=application/json\r\n"
)
)
);
stream_context_create($headers);
$this->data = json_decode(file_get_contents($this->query), true);
}
public function getResults (){
if (empty($this->data['items']))
return false;
$results = array();
foreach ($this->data['items'] as $item) {
if (!isset($item['id']['videoId']))
continue;
$result = $item['snippet'];
$result['link'] = 'https://www.youtube.com/watch?v=' . $item['id']['videoId'];
$result['embed_url'] = 'https://www.youtube.com/embed/' . $item['id']['videoId'];
$result['thumbnail'] = $item['snippet']['thumbnails']['default']['url'];
$results[] = $result;
}
return $results;
}
}
// Invoke with
function youtube_videos($term,$limit=5) {
$youtube = new YouTubeAPI($term,$limit);
$results = $youtube->getResults();
return !$results ? array() : $results;
}
// To Do, No guarantees - Results on Failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment