我正在构建一个小界面,以显示从YouTube频道到网页的直播视频。我得到了API密钥,我设置了它并且它有效。但后来我无法访问我从YouTube服务器上回来的json中的某些信息。
我尝试了一些东西,修复了移动中的任何休息,但我意识到有时它有效,有时它不会......我搜索其他线程,但我不能理解正在发生的事情。
所以问题是:
我的代码
<?php
header("Access-Control-Allow-Origin: *");
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
$API_KEY = 'API KEY HERE';
$ChannelID = ' CHANNEL ID HERE';
$channelInfo = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='.$ChannelID.'&type=video&eventType=live&key='.$API_KEY;
$extractInfo = file_get_contents_url($channelInfo);
$extractInfo = str_replace('},]',"}]",$extractInfo);
$showInfo = json_decode($extractInfo, true);
if($showInfo['pageInfo']['totalResults'] === 0){
echo 'Users channel is Offline';
}else{
echo 'Users channel is LIVE!';
}
$videoId = $extractInfo['items'][0]['id']["videoId"];
if ($videoId = 0) {
echo "<h2>No live stream yet.</h2>";
} else {
echo "</h2>$videoId</h2>";
}
?>
我需要的是:
当我回应$extractInfo
时,我得到了
{
"kind": "youtube#searchListResponse",
"etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/yOWNawoTMP4atq-Ylgqt-1puBAQ\"",
"regionCode": "NL",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
},
"items": []
} 0
如果您向我们显示的响应已完成,那么如果您获得一个离线通道,那么items数组将被发送但是为空,因此您的代码需要检查这种可能性
// only run this if we actually have an array to process
if ( count($showInfo['items']) > 0 ) {
$videoId = $showInfo['items'][0]['id']["videoId"];
if ($videoId = 0) {
echo "<h2>No live stream yet.</h2>";
} else {
echo "</h2>$videoId</h2>";
}
} else {
echo "No items in the array";
}