MailChimp API v3.0 Get Lists in PHP

You could also get only lists that include a specific subscriber’s email address, or get the lists, created in between of specific time period.

#mailchimp  /  April 12  /   21

First of all — when do you need to get the information about MailChimp lists in account? It is not such a popular function like subscribing and unsubscrubing users but it is also very useful.

For example it lays in a base of my plugin which allows to synchronize the subscribers from a specific list with your WordPress website users (any role or membership plan).

MailChimp API cURL connection function for any purposes #

No matter what task stands in front of you, the MailChimp cURL connection always looks the same. Only parameters are different. And of course your server should support cURL.

From now I will refer to this function from another posts about MailChimp API.

function rudr_mailchimp_curl_connect( $url, $request_type, $api_key, $data = array() ) {
	if( $request_type == 'GET' )
		$url .= '?' . http_build_query($data);
 
	$mch = curl_init();
	$headers = array(
		'Content-Type: application/json',
		'Authorization: Basic '.base64_encode( 'user:'. $api_key )
	);
	curl_setopt($mch, CURLOPT_URL, $url );
	curl_setopt($mch, CURLOPT_HTTPHEADER, $headers);
	//curl_setopt($mch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
	curl_setopt($mch, CURLOPT_RETURNTRANSFER, true); // do not echo the result, write it into variable
	curl_setopt($mch, CURLOPT_CUSTOMREQUEST, $request_type); // according to MailChimp API: POST/GET/PATCH/PUT/DELETE
	curl_setopt($mch, CURLOPT_TIMEOUT, 10);
	curl_setopt($mch, CURLOPT_SSL_VERIFYPEER, false); // certificate verification for TLS/SSL connection
 
	if( $request_type != 'GET' ) {
		curl_setopt($mch, CURLOPT_POST, true);
		curl_setopt($mch, CURLOPT_POSTFIELDS, json_encode($data) ); // send data in json
	}
 
	return curl_exec($mch);
}
$url, $request_type
(string) You can find both $url and $request_type in MailChimp API reference easily.

Where to get URL and request type for API connection

So, the request type is GET and the URL is https://{API PREFIX}.api.mailchimp.com/3.0/lists/. API prefix is the last part of your API key, for example us8, us10 etc.

$api_key
(string) Do not know where to obtain API key? Check this small guide.
$data
(array) This is the associative array of parameters to send to MailChimp API, it supports both query string parameters (GET) and request body parameters (POST, PATCH, PUT).

Get your lists. How to get only lists that include a specific subscriber’s email

$api_key = 'YOUR API KEY HERE';
 
// Query String Perameters are here
// for more reference please vizit http://developer.mailchimp.com/documentation/mailchimp/reference/lists/
$data = array(
	'fields' => 'lists', // total_items, _links
	//'email' => 'misha@rudrastyh.com',
	'count' => 5, // the number of lists to return, default - all
	'before_date_created' => '2016-01-01 10:30:50', // only lists created before this date
	'after_date_created' => '2014-02-05' // only lists created after this date
);
 
$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/';
$result = json_decode( rudr_mailchimp_curl_connect( $url, 'GET', $api_key, $data) );
//print_r( $result);
 
if( !empty($result->lists) ) {
	echo '<select>';
	foreach( $result->lists as $list ){
		echo '<option value="' . $list->id . '">' . $list->name . ' (' . $list->stats->member_count . ')</option>';
		// you can also use $list->date_created, $list->stats->unsubscribe_count, $list->stats->cleaned_count or vizit MailChimp API Reference for more parameters (link is above)
	}
	echo '</select>';
} elseif ( is_int( $result->status ) ) { // full error glossary is here http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
	echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
}
  • Uncomment line #7 to restrict the results only to lists which include the subscriber with a specific email.
    	//'email' => 'misha@rudrastyh.com',
  • If you want to look at the error reporting in action — just try to use incorrect MailChimp API.
  • Comment line #6 and use print_r( $result); at line #15 to view the full API response.
MailChimp API - get Lists

Only the best of WordPress

Subscribe to this weekly newsletter to receive the latest blog posts by email.I respect your privacy. Your email is safe with me.

Comments 21

  • Excellent! You just made my life easier :D

  • Wow! It’s Good!
    Your code is useful for me!
    Thanks!

  • Thank you for this! I have a question, though: how can I sort the lists by name? They seem to be sorted by creation date by default.

    • MishaAuthor January 21, 2017 at 10:40

      Hi,

      first of all add somewhere this function:

      function misha_sort_lists_by_name( $list1, $list2 ) {
      	return strnatcmp( $list1->name, $list2->name );
      }

      by the second step, before you print $result->lists, you have to sort it.

      usort( $result->lists, 'misha_sort_lists_by_name' );

      I think you can add the second piece of code just after this if( !empty($result->lists) ) {

  • Thanks so much for this! It works fantastic on GETs, but on DELETE, it returns

    stdClass Object ( [type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/ [title] => Method Not Allowed [status] => 405 [detail] => The requested method and resource are not compatible. See the Allow header for this resource’s available methods. [instance] => )

    I sent back the same $body object I got from the GET (after inserting the subscribers into my own database). Any ideas how to get around this?

    Thanks very much!

    • MishaAuthor March 20, 2017 at 08:28

      Hi Karen,

      is your code looks like this?

      $url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5( $email );
      $result = rudr_mailchimp_curl_connect( $url, 'DELETE', $api_key );

      DELETE method returns nothing for me, but it works as expected.

  • This is fantastic.

    I’m building a subscribe/unsubscribe tool. I wanted to display all the lists as a checkbox, and have the lists the user is subscribed to checked.

    I’m currently creating two queries. One to get all lists and another for lists filtered by the email address. Any ideas if this is possible with a single query?

    Cheers

  • This is enormously useful, however I want to get campaigns not lists (for one Listid), however I can use the GET/campaign-search but I am struggling to find the format for the query string to tell it to search for only a specific listid.

    Got any ideas?

    • Hi Brian,

      did you try this?

      $data = array(
      	'list_id' => 'YOUR LIST ID'
      );
      $url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/campaigns/';
      $result = json_decode( rudr_mailchimp_curl_connect( $url, 'GET', $api_key, $data) );
      • I get

        “400: Please provide ‘query’ parameter in the query string to search”

        So I tried

        $data = array(
        	'query' => 'list_id = YOUR LIST ID'
        );

        and it returned an empty set (but no error message)

      • Brian,

        I’ve just tried the example from my previous comment and everything works perfectly.

        • aha – that is because you are using “campaigns” not “campaign-search”. Ok, as you say that works now – thanks.

          However there are a lot more campaigns than that for this list, but it is only returning 10 of them. I tried changing the timeout (which I suspect is ony 10 by co-incidence). How can I get all of them?

        • Ok, great :)

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email