Google Analytics API PHP Class Update April 30th 2009
Posted April 30th, 2009 in PHP
Thanks to the several people who emailed me with questions etc about my PHP class for accessing the Google Analytics API. The most common issue was when making a request for data and nothing came back. I've addressed this issue by adding some error triggering in the code and also a note in the example about the correct formatting for the profile id.
The updated class can be downloaded here. It's now a .tar.gz file (previously it was a single file, .gz compressed) which contains the class file and a separate test file.
The profile id
The most common issue people were experiencing was that they could log in OK, but when they made a request using the data() function nothing was returned.
The first parameter for the data() function is the profile id. This profile id starts with ga: followed by an integer; it's not just the integer on its own.
So this is correct:
$api->data('ga:123456', ...);
and this is not correct:
$api->data(123456, ...);
I've modified the ->call() function so it now triggers the following errors depending on the response code that's come back from the Analytics API:
if($info['http_code'] == 200) {
$return = $output;
}
elseif($info['http_code'] == 400) {
trigger_error('Badly formatted request to the Google Analytics API; check your profile id is in the format ga:12345 and dates are correctly formatted', E_USER_WARNING);
}
elseif($info['http_code'] == 401) {
trigger_error('Unauthorized request to the Google Analytics API', E_USER_WARNING);
}
else {
trigger_error("Unknown error when accessing the Google Analytics API, HTTP STATUS {$info['http_code']}", E_USER_WARNING);
}
Could not connect at all
Kyle from www.e-strategy.net could not connect at all and found by adding the following it would work for him, so I added this to the curl init:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Incidentally, he was running PHP on a Windows box and I was running it on a Linux box (Debian 5 to be precise) from the command line, so I'm guessing there's some difference in the default CURL settings between the two.
Any further suggestions or comments
If you have any further suggestions or comments about my Google Analytics API PHP class then please feel free to contact me and I'll see what I can do. I'll post up a couple of useful summary scripts I'll be using myself in the next couple of days.
Related posts:
- The Google Analytics API and PHP: A series (Tuesday, April 28th 2009)

Comments
blog comments powered by Disqus