Valkay
Valkay

Reputation: 193

YouTube Channel Videos List in PHP with YouTube v3 API not Working

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

Answers (2)

johnh10
johnh10

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

Akhilesh B Chandran
Akhilesh B Chandran

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:

Upvotes: 1

Related Questions