Skip to content

Instantly share code, notes, and snippets.

@ashleydw
Created July 13, 2011 12:25
Show Gist options
  • Save ashleydw/1080204 to your computer and use it in GitHub Desktop.
Save ashleydw/1080204 to your computer and use it in GitHub Desktop.
Add entries from a tab separated list to MailChimp
<?php
/**
* @version 1
* @author Ashley White, http://www.needathinkle.com/
* @license http://creativecommons.org/licenses/by-sa/3.0/
*/
require 'mailchimp/MCAPI.class.php';
include 'krumo/class.krumo.php';
AddToMailChimp::process();
class AddToMailChimp {
const FILE = 'FILENAME.txt'; //Your file of rejected emails (tab seperated)
const API_KEY = 'KEY';
const LIST_ID = false; //If you know this, use it. Otherwise use the below (this is not the ID shown as a GET param on the website!)
const LIST_NAME = 'LIST_NAME';
//This array sets what your fields are and defaults. You must have EMAIL
private static $_MAP = array('EMAIL'=>'', 'COMPANY'=>'', 'FNAME'=>'', 'LNAME'=>'', 'TITLE'=>'');
public static function process() {
$entries = array();
if(!file_exists(self::FILE))
throw new Exception('Input file doesn\'t exist');
if (($handle = fopen(self::FILE, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
$e = self::$_MAP;
$i = 0;
foreach(self::$_MAP as $key=>$default) {
if(isset($data[$i]))
$e[$key] = $data[$i];
else
$e[$key] = $default;
$i++;
}
$entries[] = $e;
}
fclose($handle);
}
echo sprintf('<p>There are %d entries to process</p>', count($entries));
krumo($entries);
$mailchimp = new MCAPI(self::API_KEY);
//Get list ID. You should store this output
if(!self::LIST_ID || self::LIST_ID == '') {
if(self::LIST_NAME == '' || !self::LIST_NAME)
throw new Exception('LIST_NAME must be set.');
$list = $mailchimp->lists(array('list_name'=>self::LIST_NAME));
if($mailchimp->errorCode) {
echo '<p>Error getting list: '.$mailchimp->errorCode.': '.$mailchimp->errorMessage.'</p>';
exit;
} else {
$listId = $list['data'][0]['id'];
echo sprintf('<p>List ID: %s. You should store this in LIST_ID.</p>', $listId);
}
} else
$listId = self::LIST_ID;
$failed = $success = array();
foreach($entries as $entry) {
$merge = $entry;
unset($merge['EMAIL']);
$process = $mailchimp->listSubscribe($listId, $entry['EMAIL'], $merge, 'html', false, false, true, false);
if($mailchimp->errorCode) {
if($mailchimp->errorMessage == sprintf('Invalid MailChimp List ID: %d', self::LIST_ID))
throw new Exception('Your list ID is wrong');
$failed[] = array($entry['EMAIL'], $mailchimp->errorCode, $mailchimp->errorMessage);
} else
$success[] = array($entry['EMAIL']);
}
echo sprintf('<p>%d Failed:</p>', count($failed));
krumo($failed);
echo sprintf('<p>%d Succeeded:</p>', count($success));
krumo($success);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment