Skip to content

Instantly share code, notes, and snippets.

@dawalama
Last active September 21, 2018 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dawalama/34155428ff8f53e4d508 to your computer and use it in GitHub Desktop.
Save dawalama/34155428ff8f53e4d508 to your computer and use it in GitHub Desktop.
A utility script to export events from mix-panel
<?php
// Based on https://mixpanel.com/docs/api-documentation/exporting-raw-data-you-inserted-into-mixpanel
class MixpanelExport {
private $api_url = 'https://data.mixpanel.com/api/2.0/export';
private $api_key;
private $api_secret;
public $debug;
public function __construct($api_key, $api_secret) {
$this->api_key = $api_key;
$this->api_secret = $api_secret;
$this->debug = false;
}
public function export($params) {
if (empty($params)) {
return false;
}
if (!isset($params['api_key'])) {
$params['api_key'] = $this->api_key;
}
if (!isset($params['expire'])) {
$current_utc_time = time() - date('Z');
$params['expire'] = $current_utc_time + 100000; // Default 10 minutes
}
$sig = $this->signature($params);
$request_url = $this->api_url . '?sig=' . $sig . '&'. http_build_query($params);
if ($this->debug) {
echo "\nURI: $request_url\n";
}
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $request_url);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl_handle);
curl_close($curl_handle);
return $data;
}
private function signature($params) {
/**
* Algorithm to generate signature
*
* args = all query parameters going to be sent out with the request
* (e.g. api_key, unit, interval, expire, format, etc.) excluding sig.
*
* args_sorted = sort_args_alphabetically_by_key(args)
*
* args_concat = join(args_sorted)
*
* # Output: api_key=ed0b8ff6cc3fbb37a521b40019915f18&event=["pages"]
* # expire=1248499222&format=json&interval=24&unit=hour
*
* sig = md5(args_concat + api_secret)
**/
ksort($params);
$param_string = '';
foreach ($params as $key=>$value) {
$param_string .= $key . '=' . $value;
}
return md5($param_string . $this->api_secret);
}
}
/** Example usage
*
* $api_key = "<your api key>";
* $api_secret = "<your secret key>";
* $params = [
* 'from_date'=>'2014-01-01',
* 'to_date'=>'2014-02-01',
* 'event'=>["event-x"]
* ];
*
* $exporter = new MixpanelExport($api_key, $api_secret);
* echo $exporter->export($params);
**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment