sandro
sandro

Reputation: 11

Get latest video from youtube channel

I want to put the latest video from my channel on my website. This returns the following error:

Warning: file_get_contents(https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCD---------&maxResults=1&key=A---------------): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in C:\xampp\htdocs\inc\latestVideo.php on line 15

My code:

<?php

$API_key    = 'A---------------';
$channelID  = 'UCD---------';
$maxResults = 1;

$videoList = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));

    if(isset($item->id->videoId)){
        echo '<div class="youtube-video">
                <iframe width="280" height="150" src="https://www.youtube.com/embed/'.$item->id->videoId.'" frameborder="0" allowfullscreen></iframe>
                <h2>'. $item->snippet->title .'</h2>
            </div>';
    }

?>

Upvotes: 1

Views: 204

Answers (1)

Somangshu Goswami
Somangshu Goswami

Reputation: 1138

You should actually be doing a curl

curl \
    'https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw&maxResults=1&key=[YOUR_API_KEY]' \
     --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
     --header 'Accept: application/json' \
     --compressed

Notice how an Authorization bearer token is required on the header in addition to the API key. Also channelId needs to be id.

To understand how to do a curl call from PHP check this out -> php curl: I need a simple post request and retrival of page example

Reference of the api is here -> https://developers.google.com/youtube/v3/code_samples/code_snippets?apix_params=%7B%22part%22%3A%22snippet%2CcontentDetails%2Cstatistics%22%2C%22id%22%3A%22UC_x5XG1OV2P6uZZ5FSM9Ttw%22%7D&apix=true

You can even try in the interactive editor.

Upvotes: 2

Related Questions