php - 为什么这个 file_get_contents() 有时有效,有时无效?

标签 php api youtube file-get-contents

我正在构建一个小界面来显示从 YouTube channel 到网页的直播视频。我得到了 API key ,我设置了它并且它工作了。但是后来我无法访问从 YouTube 服务器返回的 json 中的某些信息。

我尝试了一些东西,修复了旅途中的任何中断,但我意识到有时它有效,有时它不......我搜索了其他线程,但我无法再理解发生了什么。

所以问题是:

  • 如何每次使用 file_get_contents_url() 获取有关 Youtube channel 的信息而不会出现 HTTP 响应失败?
  • 为什么我的测试使用我拥有的所有单元作为 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>";
    }
    ?>
    

    我需要的是:
  • 访问我的 YouTube channel ,
  • 获取内容为 json,
  • 把它变成一个php数组,
  • 我在哪里获得直播视频的 videoId
  • 并显示它。

  • 当我回显 $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/

    相关文章:

    php - 通过 PHP foreach 循环按钮将数据提交到 mysql 数据库的单行

    php - Laravel 4 旧的 mysql 凭据似乎在某处兑现?

    javascript - Google Analytics API for Apps 脚本中的有机搜索段

    api - 设计一个 Restful api : naming URIs, 自定义 header ?

    laravel - 如何测试 Laravel 资源

    php - Ajax 从 Mysql 检索数据 - 无法正常工作

    ruby-on-rails - 希望将YouTube视频数据存储到我的Rails数据库中

    php - 如何正确使用 Zend Youtube API?

    javascript - 需要延迟加载 iframe

    javascript - 当我尝试将 JSON 编码数组发送到 jquery 时,发生 500 内部服务器错误