File_get_contents lead time if too long

Hi friends.
I’m on page 20 output channels, their headers.
The page is loaded for a long time to solve the problem?

Example:Check stream status

<?php $start = microtime(true); $channel = "versuta"; $json_file = @file_get_contents("https://api.twitch.tv/kraken/streams/{$channel}", 0, null, null); $json_array = json_decode($json_file, true); if ($json_array['stream'] == null) {echo 'offline' } else { echo 'online' } $time = microtime(true) - $start; printf('Time of loading %.4F s.', $time); ?>

Result: OFFLINE Time of loading 0.8799 s.

0.8799 s. is for 1 stream check, and for 20=0.8799*20… tooo long
How to solve a problem?
Sorry for my bad English

A few things you can improve on.

  • Get all of them using a single request: https://api.twitch.tv/kraken/streams?channel=channel1,channel2,and,so,on
  • Load the page first and make the API call on the client-side, allowing you to show a friendly loading icon or something else.
  • Use cURL instead of file_get_contents. file_get_contents won’t allow you to handle errors or send the Client ID well at all.

And here is an example of how to create a php function to replace file_get_contents:

<?php

$clientID = array(
‘Client-ID: 0000000000000000000000000000000’
);

function file_get_contents_curl($url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
curl_setopt($ch, CURLOPT_HTTPHEADER, $clientID);
$data = curl_exec($ch);
curl_close($ch);
return $data;

}

$apiCALL = json_decode(@file_get_contents_curl(‘https://api.twitch.tv/kraken/channels/matt_thomas/follows?limit=1’), true);
$follower = $apiCALL[‘follows’][‘0’][‘user’][‘name’];
echo $follower;

?>

Thanks
https://api.twitch.tv/kraken/streams?channel=channel1,channel2
This url don’t show offline streamers… :frowning:

The /streams/ endpoint is for someone who is live. General channel information is in the /channels/ endpoint.

At this time, /channels/ does not take multiple names. Individual requests would be required.
https://api.twitch.tv/kraken/channels/channel1
https://api.twitch.tv/kraken/channels/channel2

If you mean you want to check online/offline status, you can still use the streams?channel=a,b,c way. Since you know which streams you requested, you can assume that any streams that are not in the resulting list are offline.

1 Like

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