Reputation: 193
I am trying to fetch and display my YouTube channel videos using the YouTube v3 API. I have done the preliminary things like enabling YouTube v3 API in Google Developer console. I got this code somewhere on the internet and did everything as instructed, but my videos won't display.
<?php
//Get videos from channel by YouTube Data API
$API_key = 'xxxxxxxx-xxxxxxxx'; //my API key
$channelID = 'UCxxxxxxxx'; //my channel ID
$maxResults = 10;
$video_list = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));
foreach ($video_list->items as $item) {
//Embed video
if (isset($item->id->videoId)) {
echo '<div class="">
<iframe width="280" height="150" src="https://www.youtube.com/embed/'.$item->id->videoId.'" frameborder="0" allowfullscreen></iframe>
<h2>'. $item->snippet->title .'</h2>
</div>';
}
} ?>
<?php //echo count($video_list); ?>
The $video_list
array returns empty.
What am I doing wrong?
Upvotes: 2
Views: 7665
Reputation: 4185
I ran your code with my key and a sample channel and the videos displayed fine.
Copy the finished url to your browser and check the results to verify the API is returning what you expect.
Upvotes: 4
Reputation: 6608
I think you are using a very old example code. Google has a PHP library called Google API PHP Client which will take care of the authentication etc. Try using that.
You would also get sample PHP code in their documentation page:
Search: https://developers.google.com/youtube/v3/docs/search/list
Videos: https://developers.google.com/youtube/v3/docs/videos/list
Upvotes: 1