Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Command Line PHP script to fetch e-mail addresses for all tickets that containing a specific term.
<?php
/**
* Script Name: Zendesk API Command Line
* Description: Run directly from the command line using "php -f zendesk-api.php $query".
* Version: 1.0.0
* Author: Devin Price
*/
// Credentials not stored in version control, request in order to run script
$id = 'user@example.com';
$pass = 'password';
// This is the query term passed to script
$query = $argv[1]; // i.e. "sale"
$url = 'https://branchbasics.zendesk.com/api/v2/search.json?query=' . $query;
$api = 'https://' . $id . ':' . $pass . '@example.zendesk.com/api/v2/search.json?query=' . $query;
echo "Fetching ZenDesk results from:\n";
echo $api . "\n";
// Get Tickets
function get_tickets( $url, $id, $pass ) {
// Initiate curl
$ch = curl_init();
// Set Auth
curl_setopt( $ch, CURLOPT_USERPWD, $id . ":" . $pass );
// Will return the response, if false it print the response
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Set the url
curl_setopt( $ch, CURLOPT_URL, $url );
// Execute
$response = curl_exec( $ch );
// Closing
curl_close($ch);
// Convert JSON to array
$response = json_decode( $response, true );
return $response;
}
// Gets emails
function get_emails( $response ) {
$emails = array();
if ( isset( $response['results'] ) ) :
$tickets = $response['results'];
foreach ( $tickets as $ticket ) {
if ( isset( $ticket['via']['source']['from']['address'] ) ) {
// echo $ticket['via']['source']['from']['address'] . "\n";
$emails[] = $ticket['via']['source']['from']['address'];
}
}
endif;
return $emails;
}
// Get results
function get_results( $url, $id, $pass ) {
$emails = array();
while ( false != $url ) {
$response = get_tickets( $url, $id, $pass );
$new_emails = get_emails( $response );
// Merge with any previous results
$emails = array_merge( $emails, $new_emails );
// We'll loop all pages are fetched
if ( isset( $response['next_page'] ) ) {
echo "Fetching next page of results.\n";
$url = $response['next_page'];
} else {
$url = false;
}
}
// Return all fetched emails
return $emails;
}
$results = get_results( $url, $id, $pass );
// Sort the results
$results = array_unique( $results );
echo "\n";
// Output results
foreach( $results as $email ) {
echo $email . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment