Codeigniter and the Mailchimp Export API v1.0

The Mailchimp Export API is a useful tool when you want to sync data sources. You use it to download dump of all your subscriber data.

First set up your Mailchimp API for Codeginiter.

Now, add a new config variable to your /config/mcapi.php file.

$config['mcapi_exporturl'] = 'http://us2.api.mailchimp.com/export/1.0/list'; 

To find out what your Mailchimp server center is. Get this by looking at the URL you see when you login:

Mailchimp address

Create a database table to store our data locally. We’ll only use the email address and serialised data for now, but you could do something more fancy using field headers.

CREATE TABLE `mailchimpcache` (
  `id` int(11) NOT NULL auto_increment,
  `email` varchar(255) NOT NULL,
  `extra` text NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `email` (`email`)
) ENGINE=MyISAM ;

Create a model called “mailexport” as follows:

class Mailexport extends Model {
	
	function __construct()
	{
		parent::Model();
		$this->load->library('mcapi');
	}

	/*
	* 
	* Get a dump of Mailchimp subscribers
	* 
	* @param array $params
	*                - $status 	
	*                	        optional – the status to get members for - one of (subscribed, unsubscribed, cleaned), 
	*                           defaults to subscribed
	*                - $segment 	
	*                	        optional – pull only a certain Segment of your list. For help with what this array 
	*                	        should contain: see $campaignSegmentTest(). It's also suggested 
	*                	        that you test your options against campaignSegmentTest().
	*                - $since 	
	*                	        optional – only return member whose data has changed since a GMT timestamp – in YYYY-MM-
	*                	        DD HH:mm:ss format 
	*               Example:
	*               $params = array(
	*              					'status' => "",	
	*               				'segment' => "",	
	*               				'since' => "",
	*               				);
	* 
	* @returns array 
	*                - error
	*                	        "failed to access url" indicates an error with url
	*                	        "yes" indicates a Mailchimp error like "Invalid API Key", see the $obj var for details
	*                	        "no" indicates all is good
	*                - url
	*                	        "failed to access url" indicates an error with url
	*                - headers
	*                	        if error = no, an array of field titles
	*                - data
	*                	        if error = no, an array of subscriber email addresses
	*                - obj
	*                	        if error = yes, contains the last error returned by mailchimp
	*/	
	function getexport($params = array())
	{
		$apikey = $this->config->item('mcapi_apikey');
		$list_id = $this->config->item('mcapi_list_customers');
		$value_pairs = $this->get_value_pairs_from_param($params);
		$chunk_size = 4096; //in bytes
		$url = 'http://us2.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id.$value_pairs;
		//echo $url;

		// output vars
		$headers = array();
		$data = array();
		$obj = array();
	
		// process
		$handle = @fopen($url,'r');
		if (!$handle) {
		  return array("error"=>"failed to access url", 'url'=>$url);
		} else {
		  $i = 0;
		  $c = 0;
		  while (!feof($handle)) {
			$buffer = fgets($handle, $chunk_size);
			if (trim($buffer)!=''){
			  $obj = json_decode($buffer);
			  if (is_array($obj))
			  {
				  if ($i==0)
				  {
					// get header
					foreach ($obj as $key=>$val)
					{
						$headers[$key] = $val;
					}
				  }
				  else
				  {
					// get data
					$data[] = array('email'=>strtolower($obj[0]), 'extra'=>serialize($obj));
				  }
				  $i++;
			  }
			  else
			  {
				  // error with mailchimp
				  return array("error"=>"yes", 'url'=>$url, 'obj'=>$obj);
			  }	  
			}
		  }
		  fclose($handle);
		  return array("error"=>"no", 'url'=>$url, 'headers'=>$headers, 'data'=>$data);
		}
	}
	
	private function get_value_pairs_from_param($params = array())
	{	
		$par = array();
		if (!empty($params))
		{
			foreach ($params as $key => $val) 
			{
				if ($val <> "")
				{
					$par[] = "$key=$val";
				}
			}
		}
		return (!empty($par)) ? "&".implode("&",$par) : "";	
	}

}

Then create a controller to get the data into a database… or anything else.

class Getmailchimp extends Controller {

	function Getmailchimp()
	{
		parent::Controller();
		$this->load->model('mailintegration');
	}

	
	function index()
	{
		$mailchimplist = $this->mailintegration->getexport();
		if ($mailchimplist['error'] == "no")
		{
			// do something more sexy with the $data here like save it in a db
                       // i.e. insert each row into the database table we created 
			var_dump($mailchimplist); 
		}
		else
		{
			// handle your errors!
			echo $mailchimplist['error'];
			if (isset($mailchimplist['obj'])) var_dump($mailchimplist['obj']); 
		}
		
	}

}