<?php

$resource = ''; // put the name of the endpoint here, for example organizations, tickets
$start_page = 1; // first page you want to load 
$end_page = 10; // last page you want to load (it could take a while if too big)
$subdomain = ''; // your zendesk subdomain
$userpwd = ''; // your zendesk username and password, or username/token and api token.  -  {username}/token:{token} or {username}:{password}

function makerequest($url, $userpwd) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERPWD, $userpwd); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	curl_setopt($ch, CURLOPT_VERBOSE, TRUE); 
	$result = curl_exec($ch);
	
	if (curl_errno($ch)) $result = curl_error($ch);
	curl_close($ch);
	return $result;
}

function getpages($resource, $start_page, $end_page, $userpwd, $subdomain){

	$url = isset($url) ? $url : "https://$subdomain.zendesk.com/api/v2/$resource.json";
	$i = $start_page;
	$array = Array();
	while (1) {
		if ($i > $end_page) {
			$file = fopen("results.json", "w") or exit("Unable to open file!");
			fwrite($file, json_encode(array($resource => $array)));
			fclose($file);
			break;
		}
		$results = json_decode(makerequest($url, $userpwd));
		$array = array_merge($array, $results->$resource);
		$url = $results->next_page;
		$i++;		
	}	
}
getpages($resource, $start_page, $end_page, $userpwd, $subdomain);

?>