Code – PHP Snippet Chess.com API Stats

I had this on the other site, just adding here. I often try to create little snippets on my iPad using DraftCode a local php environment, which had a new update today btw. I plan to improve this in the future, possibly WordPress shortcode plug-in. When I put this together I was just wondering how to easily grab some particular info from the JSON string.

This uses the read only API info from Chess.com, you will need to change the username to get your own stats located in the url for the $meh variable on line 3 and then parse for your particular set of stats, my example is showing Rapid Games plus Rating and then Puzzle aka Tactics Rating since I have ratings in those. The weird $poop variables are parsing the string for my specific data to show.

Note this code assumes rated games played for the types listed, there isn’t proper error checking so you will get errors if username or stats type is invalid. This is only meant to be an example used to learn with, I hadn’t used file_get_contents or json_decode before this.

<?php

$meh = file_get_contents('https://api.chess.com/pub/player/username/stats');
$obj = json_decode($meh);
$poop = $obj->chess_rapid->last->rating;
$poop2 = $obj->tactics->highest->rating;

// This line is long to show the W L D stats in one line.
$poop3 = 'W:'.$obj->chess_rapid->record->win.' L:'.$obj->chess_rapid->record->loss.' D:'.$obj->chess_rapid->record->draw;

echo 'Rapid Record: '.$poop3.'<br>';
echo 'Rapid Rating: '.$poop.'<br>';
echo 'Puzzle Rating: '.$poop2.'<br>';

?>

Leave a Comment