Objective: To download the data from the ticket export endpoint to a CSV file. The reason for this is because many customers want to analyze their Zendesk data in a secondary program (other then GoodData) such as Excel.
Notes: While we are developing and testing our code we'll want to use the sample endpoint which gives us the same sample data over and over. The purpose of this is that the sample endpoint is more forgiving and developed for this very purpose.
We now have a file handler that is stored in the variable $fh. When we refer to things we will be doing with our new CSV file we will use that variable.
The ticket export endpoint requires a date/time stamp that is in a specific format called UTC Epoch time. Without getting overly technical this is a timestamp, in seconds, since some point in time long ago. To do this we'll use two functions.
This sets the timezone to UTC:
This tells our program how far back we want to go.
$time = strtotime("-8 hours");
You might be wondering what that means? The ticket export endpoint gives us all tickets that were touched between two time periods. The hitch is that the ending time period is always now (ie: when we run the command). The shortest increment we can go back is 5 minutes. In this case we are going to pull a list of tickets from the last 8 hours.
Now we need to create the header of our CSV. The header usually contains all the column headings we want to use. To create this heading we'll copy the first row of data to a variable called $first. Then we'll convert this to an array (since it started out as an object, if this doesn't make sense, don't worry!) and finally, we'll flip it so that all the values are keys and the keys are values.
Now we have a column headings in the array called $keys. We need to write this to our CSV. We use the function fputcsv:
fputcsv($fh, $keys, ",", "\"");
As you can see, fputcsv takes 4 arguments: the file handler ($fh), the array of data to write (in this case, the keys), the delimiter (ie: comma) and the character to use to encapsulate each field (you should stick with the quote mark ("). For the last paramater, you'll need to "escape" the quote. To do this simply but a backslash before the quote mark so php knows that the quote character is being referenced.
Finally, we iterate through each result we got from Zendesk and write it to the file we are working on. We do this like so:
As you can see above, we need to convert (like we did before) from an object to an array. We do this the same way as before by putting (array) infront of the variable. This is known as casting.
The last thing we do is "close" the file we are working on. We do this with this command:
4. The Final Product
When you run the script you will get a CSV file back with the ticket data we were interested in. I have added to the GitHub repository a sample of the kind of file we will get back from the process. It is called tickets.csv.