Search code examples
phptwitch

Getting Twitch followers using Twitch API in PHP


What I'm trying to do is make a twitch follower alert in PHP. The only stuff so far that I have gotten done is find out where to get the info from. I need assistance decoding the info, and then getting the user name and setting it to a string. The place for the recent followers is: https://api.twitch.tv/kraken/channels/trippednw/follows/?limit=1


Solution

  • The data Twitch's API gives you is in JSON format (JavaScript Object Notation). You can decode it using json_decode($data, true). This gives you an associative array with the required fields. For example, to get the name of the user who most recently followed:

    json_decode($twitch_data, true)['follows'][0]['user']['name']
    

    Update:

    Here's a more detailed answer. First, you're going to have to get the data from the Twitch API via a get request using file_get_contents(). Then, you parse the resulting JSON using the method described above and echo that out onto the page. Here's the full code:

    <?php
    $api_url = 'https://api.twitch.tv/kraken/channels/trippednw/follows/?limit=1';
    $api_data = file_get_contents($api_url);
    $last_follow = json_decode($api_data, true)['follows'][0]['user']['name'];
    echo "The last user to follow <strong>trippednw</strong> on Twitch is <strong>" . $last_follow . "</strong>.";
    ?>