29 Responses

  1. Mike Street says:

    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)

    // Include Mailchimp PHP Lib
    
    $config = array (
        'mailchimp' => array (
            'api_key' => '123'
        )
    );
    
    $file = 'data.json';
    
    $mc = new Mailchimp($config['mailchimp']['api_key']);
    $campaigns = $mc->campaigns->getList(array('status'=>'sent')); // Only get sent campaigns
    
    foreach($campaigns['data'] as $i => $c) {
            $date = new DateTime($c['send_time']);
            $data['campaigns'][] = array(
                    'subject' => $c['subject'],
                    'archive_url' => $c['archive_url'],
                    'date_sent' => $date->format('jS F Y')
            );
    }
    
    $data = json_encode($data);
    file_put_contents($file, $data);
    

    And then in my website code I can simply:

    <?php $data = json_decode(file_get_contents(dirname(__FILE__) . '/data/data.json'));?>
    <ul class="list">
    <?php foreach($data->campaigns as $c) : ?>
        <li>
            <a href="<?=$c->archive_url?>"><h3><?=$c->subject?> <time><?=$c->date_sent?></time></h3></a>
        </li>
    <?php endforeach; ?>
    </ul>
    
    • 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!

  2. Bryan says:

    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

  3. partha says:

    Good to read. Thanks…

  4. B. M. says:

    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.

    
    require_once('DrewmMailChimpApiWrapper.php'); // the wrapper from drewm
    // open connection to database
    // (this I actually put into an external class, because it is used by other scripts)
    $host = 'localhost';
    $username = 'usernameOfDB';
    $passwort = '1234'; // whatelse :-)
    $db_name = 'nameOfDB';
    $link = mysql_connect($host, $username, $passwort) or die('connection-parameters not correct!');
    mysql_select_db($db_name) or die('no connection to selected db possible!');
    
    $con = new Dbconnect();
    $con->db_verbindung_oeffnen('nameOfDB');
    
    // open connection to mailchimp-api
    $MailChimp = new \Drewm\MailChimp('my-mailchimp-api-key'); // Drewm = namespace which is used in the DrewM-script
    
    $mc = $MailChimp->call('lists/list');
    foreach($mc[data] as $listen)
    {
    //	echo "listeid: " . $listen[id];
    //	echo "liste name: " . $listen[name];
    //	echo "anzahl: " . $listen[stats][member_count];
    	$listid = $listen[id];
    	$listname = $listen[name];
    	$listanzahl =  $listen[stats][member_count];
    
    // before first run you have to insert the list-data into the new table; you never need this anymore, therefor you should delete it or comment it out
    // $sql = "INSERT INTO new_table_that_contains_subscriber_count (mailinglisteID, listenname, anzahl) VALUES ('".$listid."','".$listname."',".$listanzahl.");";
    
    $sql = "UPDATE new_table_that_contains_subscriber_count SET anzahl = ".$listanzahl.", listenname = '".$listname."' WHERE mailinglisteID = '".$listid."';";
    
    $eep = mysql_query($sql);
    }
    
  5. Mick Kennys says:

    Nicely explained, nicely wirtten – thank you! As I am a newbie in such things, this was a great tutorial for me!

  6. Tech Leaks says:

    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 ….

  7. Lisa says:

    Great! This is more helpful.

  8. Gamer says:

    Thanks for the great tut, it works.

  9. Trelat says:

    Works perfectly, thanks a lot.

  10. Rashaqah says:

    This is very helpful, their api is one of most complicated api’s out there but you made it seem easy, thanks a lot

  11. Daniel says:

    Great post, this really helped.

  12. Joshua says:

    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.

  13. Joshua Read says:

    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 )

    $MailChimp = new \SPPRAC\MailChimp('Paste your API code here);
    $result = $MailChimp->call('lists/list', array(
                    'id'                => 'Paste Your Lists ID here'
                ));
    $curr_sub_count = $result[data][0][stats][member_count];
    ?>
    <p class="sub">Join <?php echo number_format($curr_sub_count); ?> subscribers!</p>
    
  14. Designsolv says:

    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.

  15. Jacklyn says:

    Great tutorial, you think you’d find something like this in the Mailchimp docs but noooo, thanks a lot man it helped a lot

  16. 21coders says:

    I also used to do it manually but this tutorial really helped me.Thanks!

  17. Ray L says:

    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

  18. juan says:

    Thank you, great code. It worked just like charm.

  19. Cedric says:

    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

  20. Oganro says:

    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?

  21. vshingala says:

    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.

  22. Albert says:

    Is i possible to show member count of a group? I tried somethings and it didn’t work.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).