Unable to parse and loop through Twitch followers JSON response in PHP

I’m trying to fetch and show the most recent 100 followers from Twitch API on my site but I’m struggling with handling the JSON data properly.

Here’s what I have so far:

$response = file_get_contents("https://api.twitch.tv/kraken/channels/markiplier/follows.json?limit=100");
$data = json_decode($response, true);

I’m having trouble iterating through the results correctly. I attempted this approach:

foreach ($data as $item => $details) {
    echo $details['username'];
}

But it’s not working as expected. My goal is simple - I want to display a list of the latest 100 follower usernames on my webpage. I’m pretty new to working with JSON in PHP so any guidance would be appreciated. What’s the correct way to access and loop through this follower data?

You’re looping through the wrong part of the JSON response. The Twitch API nests the followers inside a ‘follows’ property, so you need to target that array specifically.

Here’s the fix:

$response = file_get_contents("https://api.twitch.tv/kraken/channels/markiplier/follows.json?limit=100");
$data = json_decode($response, true);

foreach ($data['follows'] as $follow) {
    echo $follow['user']['display_name'];
}

I made this exact mistake when I started with Twitch’s API. The follower data sits under ‘follows’, then each person’s info is in their ‘user’ object. Quick heads up - Kraken API is deprecated, so you’ll want to switch to Helix API down the road.

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