As 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.
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 \WTW\MailChimp('[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 \WTW\MailChimp('[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 insubcount.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.
Great article – I was using the Mailchimp API to retrieve the latest mailouts, to list them on the website.
Like you I was getting them once a day, but rather rely on a user request to go and get it (and thus slowing down that one users page load, which could be Google and could rank me lower) I relied on a cron job to go and do the dirty work in the middle of the night.
Upon getting the data, I would store it in an array and json_encode/decode – this meant I only needed one file (something I would suggest you do – for scalability)
And then in my website code I can simply:
Great suggestions, Mark. That’s a good tip regarding the fact that the one user visiting the page could technically be Google, although I would guess that would be pretty rare.
Thanks!
This is awesome! I’ve been wanting to do something similar to this.
It would be awesome if you had a live demo of what we’re actually accomplishing. Just a suggestion @Louis
Thanks for sharing
The live demo is on the Web Tools Weekly website.
You can’t really have a “live demo” with code for PHP though, unless maybe you use something like PHPFiddle, but I’ve never tried that. Might be worth a try I suppose.
Good to read. Thanks…
Thank you very much for this detailed tutorial which was really helpful for me!
I modified this slightly: I write the results into the database (new table with 3 columns: mailinglisteID, listenname, anzahl (“anzahl” means “number/count”). The script is run via cronjob and from my CMS I can easily access the database and get the values (which, moreover, are cached).
Perhaps somebody could need the code, therefore I put it below together with some comments.
Nicely explained, nicely wirtten – thank you! As I am a newbie in such things, this was a great tutorial for me!
Thanks for great tips …… But we have always had a bad experience with MailChimp…. We imported out list of 4000 email subscribers but each time, MailChimp put our account on hold ….
Great! This is more helpful.
Thanks for the great tut, it works.
Works perfectly, thanks a lot.
This is very helpful, their api is one of most complicated api’s out there but you made it seem easy, thanks a lot
Great post, this really helped.
Thanks for the great post, is it possible to decode the json using jquery and pass it to another php file for processing ?
I’m sure it is. I suppose you could add the data into a hidden HTML element (or cookie, or local storage?) or something like that, then grab it with jQuery and send it as a parameter via jQuery’s Ajax functions to the PHP file in question.
I’m just summarizing the theoretical method here, but you’d have to try it to see.
This was a huge help. The API has changed as well as Drew’s Code. Here is what just worked for me:
(Detailed Information for those new to this: I pasted this at the bottom of Drew’s MailChimp.php and then uploaded that file to my server. I then called example.com/MailChimp.php )
Hey Joshua,
I was wondering if it’d be possible for you to share a copy of your php file with me? I think I’ve got some incorrect syntax going on so it’d be awesome if I could see how your file is setup in entirety. My email is alexhollender@gmail.com
Thanks so much!
This was one of the sophisticated API’s and i was able to figure things out with the assistance of your tutorial. Also thanks to Mike for the further elaboration.
Great tutorial, you think you’d find something like this in the Mailchimp docs but noooo, thanks a lot man it helped a lot
its actually there somewhere but i can’t find it anymore.
I also used to do it manually but this tutorial really helped me.Thanks!
Instead of a cron job, could you use MySQL’s event scheduler and save the output in a database table?
http://dev.mysql.com/doc/refman/5.7/en/events-overview.html
Thank you, great code. It worked just like charm.
Hello, no idea if someone will read my comment as the post is pretty old.
I store in an extra Merge Field called CITY in Mailchimp the city where the people live.
I’m looking for a way to display for a given city the numbers of members from this city.
Like on the page mysite/mexico I’d want to display the numbers of subscribers in Mexico from my list.
I have no idea how to do this…
Any idea ?
Thanks
I don’t know, you’ll have to contact MailChimp directly or else try searching their API documentation.
Works perfectly, thanks a lot. but my account suspended after I imported list of 2500 email subscribers & MailChimp put our account on hold? any suggestions?
No idea. Mailchimp has good live chat support, so you should contact them directly.
Hello Friends i am new to php and i want to integrate mailchimp. First i setup that all which is mentioned in gituhub. but when at starting point i could not get any response.
Is i possible to show member count of a group? I tried somethings and it didn’t work.
Thank you for another informative blog.Thank you, great code. It worked just like charm.