为什么这个file_get_contents()有时工作,有时不工作?

问题描述 投票:0回答:1

我正在构建一个小界面,以显示从YouTube频道到网页的直播视频。我得到了API密钥,我设置了它并且它有效。但后来我无法访问我从YouTube服务器上回来的json中的某些信息。

我尝试了一些东西,修复了移动中的任何休息,但我意识到有时它有效,有时它不会......我搜索其他线程,但我不能理解正在发生的事情。

所以问题是:

  1. 如何在没有HTTP响应失败的情况下每次使用file_get_contents_url()获取有关Youtube通道的信息?
  2. 为什么我的测试使用我所拥有的所有单位作为Google API的配额? (它在50次刷新时用完了单位)

我的代码

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

我需要的是:

  1. 要访问我的YouTube频道,
  2. 得到json的内容,
  3. 把它变成一个php数组,
  4. 我在哪里获得了直播视频的videoId
  5. 并显示它。

当我回应$extractInfo时,我得到了

{
    "kind": "youtube#searchListResponse", 
    "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/yOWNawoTMP4atq-Ylgqt-1puBAQ\"", 
    "regionCode": "NL", 
    "pageInfo": { 
            "totalResults": 0, 
            "resultsPerPage": 5 
            }, 
    "items": [] 
} 0
php api youtube file-get-contents
1个回答
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";
}
© www.soinside.com 2019 - 2024. All rights reserved.