Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save conkonig/198f88b897e7555a597d94466fa51e51 to your computer and use it in GitHub Desktop.
Save conkonig/198f88b897e7555a597d94466fa51e51 to your computer and use it in GitHub Desktop.
Get latest mailchimp newsletters
<?php
// CREDIT:
// https://rudrastyh.com/mailchimp-api/get-lists.html
$api_key = 'xxxxxxxxxxxxxxxxx';
$us = 'xxx';
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_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);
}
$response = rudr_mailchimp_curl_connect('https://' . $us . '.api.mailchimp.com/3.0/campaigns/?sort_field=send_time&sort_dir=DESC', 'GET', $api_key);
$response = json_decode($response);
$campaigns = $response->campaigns;
foreach ($campaigns as $campaign) {
if (strpos(strtolower($campaign->settings->subject_line), 'good news') !== false) {
$campaignContent = rudr_mailchimp_curl_connect('https://' . $us . '.api.mailchimp.com/3.0/campaigns/' . $campaign->id . '/content', 'GET', $api_key);
$campaignContent = json_decode($campaignContent);
$html = $campaignContent->html;
$doc = new DOMDocument;
$mock = new DOMDocument;
$doc->loadHTML($html);
$body = $doc->getElementsByTagName('body')->item(0);
foreach ($body->childNodes as $child) {
$mock->appendChild($mock->importNode($child, true));
}
echo $mock->saveHTML();
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment