Search code examples
phpjsondiscord

Count discord users with JSON


I am designing a new homepage for my community and one of the features we want is a block to display how many users are connected to our team-speak and discord servers. I have the team-speak done by using the PHP framework but I am not familiar with JSON and need a bit of help.

Currently the JSON file displays all individual users, and channels etc. It doesn't not have like a "currently online" thing.

Here is the file: https://discordapp.com/api/guilds/140805434654195712/embed.json

Want I want to do is use JSON to count the individual users and then echo display the number in a PHP file.

Any help is very much appreciated!


Solution

  • This will work for you:

       <?php
    
     $jsonIn = file_get_contents('https://discordapp.com/api/guilds/140805434654195712/embed.json');
     $JSON = json_decode($jsonIn, true);
    
     $membersCount = count($JSON['members']);
    
     echo "Number of members: " . $membersCount;
    ?>
    

    What this does is take the JSON string in from your URL, then encodes the string to make it a JSON object (an array of nested arrays pretty much). The JSON string has an 'array' of members. By using a foreach loop you can count how many members objects are in that 'array'.