Menu

Google Analytics API with PHP Tutorial

Perhaps I’m spoiled, but dealing with Google’s documentation always leaves me frustrated. Often a changed interface leaves information outdated. Other times the Google engineers leave steps out because they don’t need to hold the hands of dummies like me. Well other dummies, I’m here to sort that out (at least when it comes to a very very specific use case!)

Most tutorials focus on a use case that requires some kind of user authentication. However, I want to use the API to grab data from Google at regular intervals with no human interaction, so that’s why I’m writing this up.

Why use the Google Analytics API?

You can see all of your data in the Google Analytics dashboard, right? Why do you need to access it programmatically? Here’s one reason: It can be powerful if you want to feed information about your sites traffic back into the site content itself! For example, if you want to promote your most popular pages you need to be able to query traffic information.

A rookie might think to herself, “Why use Google Analytics? I could just add a +1 to the database every time the page is viewed and not mess with this API nonsense!” Don’t do this! Writing to the database with that frequency is extremely bad practice. Google Analytics is great at storing traffic data, so we’re going to offload that part to the big G.

Connecting to Google Analytics API

If you want to avoid using git you can use the “download zip” button on the right hand side.

Unzip it, name the folder something friendly and put it on your server (you only really need SRC). You also need to put the .p12 file on your server.

Now we need to create a .php file to interact with the client. Place this file in the /examples directory alongside the other .php files. You can name it whatever you like. There are two parts to this file, first configuring all of the Google generated details with our client.

The second, is to write the API call. You need the Analytics ID to replace 1111111 below. The pieces you need to make a successful query are the ID, a date range for the traffic data (start date and end date), “metrics”, and then any optional parameters. One great way to help build the proper query is to use http://ga-dev-tools.appspot.com/explorer/