Categories
Code

How to display number of list subscribers from MailChimp in PHP with API 3.0

Today I was trying to show the total number of list subscribers for a Mailchimp list I maintain. I found some more complex solutions using API wrappers (like drewm’s wrapper on Github) but they were more complex than I needed, and still didn’t fully solve the issue – just presented the tools. 

So a friend helped me work on figuring out the 3.0 API connection to get the subscriber total, and I combined that with the method outlined here to limit the API connections to one per minute.

Here’s the code, which you’ll need to tweak slightly to get your results.

[php] <?php
$api[‘key’]= ‘INSERT-YOUR-API-KEY-HERE’;
$url=’https://INSERT-YOUR-US-DOMAIN-KEY.api.mailchimp.com/3.0//lists/INSERT-YOUR-LISTID-HERE/?apikey=INSERT-YOUR-API-KEY-HERE’;
$lastRunLog = ‘/logs/lastrun.log’;
$subfile = ‘/logs/subcount.log’;
$lastRun = file_get_contents($lastRunLog);

if (time() – $lastRun >= 60) {
// it’s been more than one minute so we will connect to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
$total= $json[‘stats’][‘member_count’];
// update lastrun.log with current time
file_put_contents($lastRunLog, time());
file_put_contents($subfile, $total);
} else {
$total = file_get_contents($subfile);
}

echo $total;
?>
[/php]

Just a few notes:

You need to create a logs directory on your server, and create two empty files there called lastrun.log and subcount.log. Rather than hit the MailChimp API with every page load, we’re caching the subscriber count in subcount.log, and checking the API each minute to get the subscriber count. You can increase that wait time even higher by editing line 8 of the code. The number 60 there is seconds. So for instance setting that to 300 would be 5 minutes, and 3600 would be one hour.

screen-shot-2016-11-16-at-1-56-18-pm

To create or find your MailChimp API key, see these instructions.

To find your listid, see these instructions.

Your “US DOMAIN KEY” is the last 3 characters of your API key (mine is us5, for instance).

3 replies on “How to display number of list subscribers from MailChimp in PHP with API 3.0”

Leave a Reply