Search code examples
phpapiyoutubefile-get-contents

Why is this file_get_contents() sometimes working and sometimes not?


I am building a small interface to show livestreamed video from a YouTube channel to a webpage. I got the API key, I set it up and it worked. But then I couldn't access certain information from the json I got back from the YouTube server.

I tried a few things, fixing whatever breaks on the go, but I realised that sometimes it works and sometimes it doesn't... I searched other threads but I can't understand anymore what's happening.

So the questions are:

  1. How to use file_get_contents_url() to get info about a Youtube channel every time without HTTP response failure?

  2. Why is my testing using all the units I have as a quota from Google's API? (It runs out of units in a 50 refreshes or so)

My code

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

What I need is:

  1. to access my YouTube channel,
  2. get the content as json,
  3. turn it into a php array,
  4. where I get the videoId of the livestreamed video
  5. and display it.

When I echo $extractInfo I get

{
    "kind": "youtube#searchListResponse", 
    "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/yOWNawoTMP4atq-Ylgqt-1puBAQ\"", 
    "regionCode": "NL", 
    "pageInfo": { 
            "totalResults": 0, 
            "resultsPerPage": 5 
            }, 
    "items": [] 
} 0

Solution

  • If the response you are showing us is complete, then if you get a channel that is offline then the items array is sent but is empty, so your code needs to check for that possibility

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