Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Last active March 28, 2017 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/9ecbd983bd692168da6180fc52b40200 to your computer and use it in GitHub Desktop.
Save joduplessis/9ecbd983bd692168da6180fc52b40200 to your computer and use it in GitHub Desktop.
<?php
/*
* The following code illustrates how to use batch operations with the
* new Mailchimp v3 API. Much of what I found on the net was half baked
* and relied on another layer of abstraction.
*
*/
$subscribers = [];
$batch_operations = [];
$apikey = "xxx-xxx";
$listkey = "xxx";
// Single subscriber array
// Ideally you would want to iterate over all your subscribers,
// and add them to the $subscribers array in the below format
$subscribers[] = [
'apikey' => $apikey,
'email_address' => "joe.soap@exmaple.com",
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => "Joe",
'LNAME' => "Soap",
]
];
// Add an operation to the batch
// Notice the PUT & the email hash:
// You don't need the email hash, but you would have to use POST then
// Use DELETE if you want to delete the subscriber
// The code below updates/adds the subscriber - POST only adds one
foreach ($subscribers as $subscriber) {
array_push($batch_operations, array(
"method" => "PUT",
"path" => "/lists/$listkey/members/".md5(strtolower($subscriber['email_address'])),
"body" => json_encode($subscriber)
));
}
// Encode the operations request
$request_encoded = json_encode(array('operations' => $batch_operations));
// Make the CURL request
$ch = curl_init();
// Set up our options for the request
curl_setopt($ch, CURLOPT_URL, "https://xxxx.api.mailchimp.com/3.0/batches");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$apikey )));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 14000);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_encoded);
// Get the result
$result = json_decode(curl_exec($ch), 1);
// Close the CURL connection
curl_close($ch);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment