Displaying Your MailChimp Subscriber Count with PHP and MailChimp’s API


Update (Nov. 19, 2016): MailChimp has recently announced that the old MailChimp API will no longer be supported after 2016. Since it was announced, the script I describe below by Drew McLellan has been updated to be compatible with the new MailChimp API 3.0. Unfortunately, I could not get Drew’s script to work in my case. I’ve opened an issue for that but I also found another script by Misha Rudrastyh that works for me and does exactly what I need, so I recommend using that solution rather than what I describe in this post.

MailChimp logoAs many of you probably know, I’ve been writing a weekly newsletter called Web Tools Weekly for over a year now. Most issues begin with a brief JavaScript tutorial, after which I include a curated list of tools primarily focused on front-end development. I’ve released a new issue every week, without a break, since July 2013 and I use MailChimp to produce the mailing (disclosure: previous link has my affiliate ID attached, which means we both get $30 towards MailChimp if you become a paying customer).

The subscriber count has grown to almost 10,000 as of this writing, and that number is growing by about 70 each week. For the past couple of months, I’ve been displaying the subscriber count on the home page, and manually editing it every once in a while.

Web Tools Weekly subscriber count

Clearly, that’s not an ideal method for doing this sort of thing – especially when MailChimp offers an API that lets you tap into your numbers and do all sorts of other stuff programmatically.

So I did some research on how to get the subscriber count to display automatically on the Web Tools Weekly home page and here’s what I came up with.

MailChimp API by Drew McLellan

The only back-end language I know how to work with on my own is PHP (and I use the phrase “know how to work with” very loosely!). Taking a quick look at MailChimp’s API docs shows that they have listed various API abstraction tools, including some for PHP.

This led me to try out Drew McLellan’s MailChimp API (Drew is the 24 ways guy, in case you’re trying to figure out why you know that name).

Drew’s script is great because it’s simple. It gives you an easy interface into the data available, then you can just mess around with it from there to get what you want.

After including the source file from Drew’s script, I modified it slightly to use my own custom namespace (i.e. I changed “Drewm” to “WTW”) and then I used his example in the docs to instantiate the main object:

include "vendor/MailChimp.php";
$MailChimp = new WTWMailChimp('[api key]');
$mc = $MailChimp->call('lists/list');

In that first line, you would replace “[api key]” with your actual API key from MailChimp. You can use this guide from MailChimp to create your key and include it when using Drew’s (or anyone else’s) script.

Once I had the object instantiated, I had no idea what the actual API consists of. So after some fiddling with PHP’s var_dump and print_r, I was able to come up with the following line of PHP to produce the number of subscribers:

$curr_sub_count = $mc[data][0][stats][member_count];

Once I have that, I can display the $curr_sub_count variable anywhere on the page, and this would show an updated subscriber count that I don’t need to manually change every week.

Limiting Calls to the API

At this point, the main problem with this code is the fact that I’m connecting to the API on every page load. MailChimp’s API has some limitations that might cause problems if the Web Tools Weekly website got a traffic spike.

All that I need to do is access the API once per day, record that value somewhere, and then use it in the page as needed. So I Googled around a bit and found this StackOverflow thread. The top-rated answer (not the one that’s checkmarked) produced the following code:

$lastRunLog = 'vendor/lastrun.log';
$subfile = 'vendor/subcount.log';
$lastRun = file_get_contents($lastRunLog);

if (time() - $lastRun >= 86400) {
    // its been more than a day so we can connect to the API
    $MailChimp = new WTWMailChimp('[api key]');
    $mc = $MailChimp->call('lists/list');
    $curr_sub_count = $mc[data][0][stats][member_count];
    // update lastrun.log with current time
    file_put_contents($lastRunLog, time());
    file_put_contents($subfile, $curr_sub_count);
} else {
    $curr_sub_count = file_get_contents($subfile);
}

Here’s a summary of what’s happening in that script:

  • The first two lines are referencing log files that I’ve placed on the server inside of a folder called “vendor”. The lastrun.log holds the time the API was last accessed, in a Unix time stamp.
  • The second log file is called subcount.log. This is where I record the subscriber count.
  • Next I grab the contents of the log, then I check to see if it’s been 24 hours since the last time the API was accessed. The number 86400 is used because that’s exactly 24 hours in Unix time, as explained in this thread.
  • If it has been 24 hours since the last API call, we run a new API call to get the new subscriber count, record the current time into lastrun.log, and update the count in subcount.log.
  • If it’s been less than 24 hours, the “else” branch is used, and we simply get the count from the subcount.log file without doing an API call.

In the HTML for the Web Tools Weekly home page, I have a line that looks like this:

<p class="sub">Join <?php echo number_format($curr_sub_count); ?> subscribers!</p>

This uses PHP’s number_format() function to make the count appear with a comma (i.e. “9,478” instead of “9478”).

And that’s it. With this chunk of code in place, I’m ensuring the API is not being unnecessarily queried. If the subscriber count changes only slightly, or not at all, in any given hour, then clearly there’s no need to connect to the API each time the page is visited. Even once a day is probably unnecessary with only about 10 new subscribers per day, but I think this is a more reasonable approach.

Other Techniques?

If you have any suggestions for any of the code above or if you have used MailChimp’s API for something similar, but using a different method, I’d love to hear your thoughts.





Source link

Leave a Reply

Your email address will not be published. Required fields are marked *