PHP Online/Offline using the Twitch API

I’m really new to PHP i’ve been studying for like 2-3 days, i manage to do a few things with the API such as get the status,followers,etc, but i can’t make work showing the offline/online, shows offline even if one of them it’s online.

        $streams = array('spiritstr','rockletztv','KScoolZb');
  	$length = count($streams);
  	 for ($i = 0; $i < $length; $i++){
        $twitch_api = json_decode(@file_get_contents(''.$streams[$i]));
        echo  "Canal: <b>".$streams[$i] ."</b><br>";
        echo "Name : " .$twitch_api->status; 
        echo "</br>Game : " .$twitch_api->game; 
        echo "</br> Followers : " .$twitch_api->followers;
  	$json_array = json_decode('$twitch_api');
  	if ($json_array['stream'] != null)
  	{ ?>
  	<br>ONLINE <?php echo ''.$streams[$i] ?>
  	<?php } else { ?>
  	<?php }   


There are a Few errors here so I’ll list them

  1. You are double json_decoding, the second call is unneeded
  2. The second call to json_decode you are decoding '$twitch_api' this decodes the string $twitch_api and fails, you need json_decode($twitch_api)
  3. You should use curl instead of file_get_contents, file_get_contents is a security reason for HTTP calls, further more there is no way to check the HTTP Status code of the response.
  4. When using curl check the HTTP Response is a 200
  5. if ($twitch_api->stream == null) will suffice for your online/offline check
  6. Avoid what you are trying to do (start processing a object then start processing the same data as an array you can iterate on the object only)
1 Like

Thanks for reply!!
1.2 Thanks didn`t realised that.
3. How do i use cURL instead of file_get_contents?
6. You mean use ‘foreach’ ?

Heres the curl docs:

I could give you the code solution but then you would learn nothing.


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.