获取来自YouTube频道的最新视频

时间:2020-05-03 14:50:22

标签: php youtube

我想将频道中的最新视频放到我的网站上。这将返回以下错误:

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

我的代码:

<?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>';
    }

?>

1 个答案:

答案 0 :(得分:1)

您实际上应该在卷曲

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

请注意,除了API密钥之外,还需要在标头上添加授权承载令牌。同样,channelId也必须是ID。

要了解如何从PHP进行curl调用,请查看-> php curl: I need a simple post request and retrival of page example

api的参考在这里-> 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

您甚至可以在交互式编辑器中尝试。