我正在构建一个小界面来显示从 YouTube channel 到网页的直播视频。我得到了 API key ,我设置了它并且它工作了。但是后来我无法访问从 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
最佳答案
如果您向我们展示的响应是完整的,那么如果您的 channel 处于离线状态,则 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";
}
关于php - 为什么这个 file_get_contents() 有时有效,有时无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902406/