28 Responses

  1. Mike Street:

    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. 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. Good to read. Thanks…

  4. 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. Nicely explained, nicely wirtten – thank you! As I am a newbie in such things, this was a great tutorial for me!

  6. 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:

    Great! This is more helpful.

  8. Thanks for the great tut, it works.

  9. Works perfectly, thanks a lot.

  10. 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. Great post, this really helped.

  12. 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. 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>
    
    • 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!

  14. 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. 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. I also used to do it manually but this tutorial really helped me.Thanks!

  17. Ray L:

    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:

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

  19. 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. 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:

    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.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.