I’m working on a Drupal project where I need to create a custom block that displays user streaming status, similar to what you see on gaming websites. I’ve set up a user field where people can input their streaming platform username.
Here’s my template code:
<?php
$start_time = microtime(true);
$username = strip_tags($fields['field_username']->content);
$api_response = json_decode(file_get_contents('https://api.twitch.tv/helix/streams?user_login='.strtolower($username)), true);
$status_text = " is currently offline";
$viewer_count = "Not streaming";
$user_game = strip_tags($fields['field_game']->content);
if (!empty($api_response['data'])) {
$stream_data = $api_response['data'][0];
$broadcaster_name = $stream_data['user_name'];
$stream_description = $stream_data['title'];
$current_category = $stream_data['game_name'];
$viewer_count = $stream_data['viewer_count']." watching";
$status_text = " is live now";
}
$end_time = microtime(true);
$response_time = $end_time - $start_time;
$milliseconds = $response_time * 1000;
?>
<div class=<?php echo "\"$user_game streamStatus\"" ?> title=<?php echo "\"$viewer_count\"" ?>>
<?php
print $milliseconds;
print $fields['username']->content;
echo "$status_text";
?>
</div>
The functionality works correctly, but my website becomes extremely slow when this block loads. Is this a problem with my implementation or is the external API naturally slow? Should I look into caching solutions or alternative approaches?