Issue with Index Out of Bounds When Fetching Data from Twitch API
I’m currently developing a PHP script that retrieves streaming information from Twitch, utilizing a list of channels saved in my database. The code is functioning to some extent, but I’m encountering this issue:
Notice: Undefined offset: 1
This error appears to arise when I iterate through the responses received from the API. Below is a snippet of my code:
<?php
// Guard against unauthorized access
if (!defined('_JEXEC')) {
die('Unauthorized access');
}
$channelList = $params->get('channels');
$channelsArray = explode(',', $channelList);
$apiUrl = "https://api.twitch.tv/streams/?channel=";
$activeStreams = array();
// Construct the URL for API request
foreach($channelsArray as $key => $channel){
if($key > 0) {
$apiUrl .= ",";
}
$apiUrl .= $channel;
}
// Retrieve data from Twitch API
$response = file_get_contents($apiUrl);
$streamData = json_decode($response, true);
// Process each channel - ERROR OCCURS HERE
foreach($channelsArray as $index => $channelName){
$channelUrl = $streamData[$index]['channel']['url'];
$urlParts = explode('/', $channelUrl);
$username = end($urlParts);
$streamTitle = $streamData[$index]['status'];
$currentGame = $streamData[$index]['game'];
$viewerCount = $streamData[$index]['viewers'];
displayStreamInfo($username, $viewerCount, $streamTitle, $currentGame);
$activeStreams[] = checkStatus($username);
}
function displayStreamInfo($streamer, $viewers, $title, $game) {
$gameIcon = ($game == "CS:GO") ? "csgo_icon.png" : "live.png";
if ($streamer != null) {
echo '<img src="./images/'.$gameIcon.'">';
echo '<a href="https://twitch.tv/'.$streamer.'" target="_blank">';
echo '<strong>'.$streamer.'</strong></a>';
echo ' ('.$viewers.' viewers) - '.$title.'<br>';
}
}
function checkStatus($user) {
return ($user != null) ? $user : null;
}
?>
I think the problem might lie in how I’m accessing indices within the arrays, but I’m not sure what the root cause is. Has anyone faced similar situations while working with API data? Any insights or recommendations would be appreciated.