Hey guys,

<?php
    $url = "https://api.twitch.tv/kraken/streams/greatbritishbg";
    $json = file_get_contents($url);
    $json = json_decode($json);
    var_dump($json);

    foreach($json->streams as $stream) {
        echo $stream->channel->stream . '<br />';
        echo $stream->channel->display_name . ' is playing ' . $stream->channel->game . '.<br />';
        echo '<a href="http://www.twitch.tv/' . $stream->channel->name . '">Watch Live</a>';
        echo '<hr />';

          $status = $stream->channel->stream;
    }
    //PSUEDO CODE:
    if($status == 'Online' {

    } else { 

    }
  ?>

I'm trying to query whether the cast is online or offline. however I'm getting a foreach error:
Warning: Invalid argument supplied for foreach() in /home2/xtrapsp/public_html/index.php on line 79

Here is a Json dump:

object(stdClass)#1 (2) { ["_links"]=> object(stdClass)#2 (2) { ["self"]=> string(51) "https://api.twitch.tv/kraken/streams/greatbritishbg" ["channel"]=> string(52) "https://api.twitch.tv/kraken/channels/greatbritishbg" } ["stream"]=> NULL } 

Thanks in advance guys

Member Avatar for diafol

streams property is not a member of $json object. It's stream. It is also set to NULL.

commented: thanks for helping the NULL part click :) +4

Hi diafol,

foreach($json->stream as $stream) { 
    echo $stream->viewers;
} 

Thanks for spotting that streams is not part of the json object. It returns Null until I'm online so that makes sense!

I've tried with someone elses channel who is currently online (I return a LOT of values in the dump.)

    $url = "https://api.twitch.tv/kraken/streams/reninsane";
    $json = file_get_contents($url);
    $json = json_decode($json);
    //var_dump($json);

    foreach($json->stream as $stream) { 
        echo $stream->viewers;
    } 

So, I'm still not returning how many viewers he has so I can rest knowing it's the json causing issues.

Currently using the for the if Online part:

https://github.com/justintv/Twitch-API/blob/master/v3_resources/streams.md#get-streams

Member Avatar for diafol

Not sure to help you. Could you show the content of the json dump?

Ended up querying it slightly differently and that appears to have worked!

Pretty much checked if status = null

Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.