Insert subscriber to MailChimp using PHP

Last Updated: January 28, 2019

$apiKey = 'your-api-key';
$list = 'your-list-id';

$data = array(
	'merge_fields' => array(
		'FNAME' => $_POST['your-email'],
		'PHONE' => $_POST['your-phone-number']
	),
	'email_address' => $_POST['your-email'],
	'status' => 'subscribed',
);

$json = json_encode($data);


$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' .  $dataCenter . '.api.mailchimp.com/3.0/lists/' . $list . '/members';


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$mailchimp_result = json_decode($result);

Add your feedback or comment below: