I'm using Drupal and want to add a Block, where the users streams are shown, like they do it on teamliquid.net.
So I do the normal stuff, adding a field to users, where they can enter their Twitch-ID and so on.
So this is my views-view-fields--streambar--block.tpl.php file:
<?php
$time_pre = microtime(true);
$channelName = strip_tags($fields['field_streamid']->content);
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName)), true);
$saveResult = " is Offline";
$currentViewer = "Offline";
$game = strip_tags($fields['field_teamuser']->content);
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$currentViewer =$json_array['stream']['viewers']." Viewers";
$saveResult = " is Online";
}
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
$sec = $exec_time * 1000;
?>
<div class=<?php echo "\"$game streamItem\"" ?> title=<?php echo "\"$currentViewer\"" ?> >
<?php
print $sec;
print $fields['name']->content;
echo "$saveResult";
?>
</div>
So far it works, but it slows down the website like hell. Is it my fault or is the API just very slow and I have to search for an workaround?
This is bound to be slow, every time a user requests your page they have to wait while your server then requests another page from another site, adding a tonne of latency to every page request. Imagine you got 200 hits at once, that's 200 people waiting for your server to go to the API 200 times, request the same information 200 times, receive and process the same information 200 times.
The proper way of doing this would be to pull from the Twitch API every few minutes/seconds depending on the update frequency you want (I'd recommend Ultimate Cron and writing a Cron function for this), cache these results to a database table then have your site pull the results from a database when pages are requested instead of having to visit the API every single time. This would lower your latency for every request and even save your server some CPU cycles.
look at hook_cron()