PHP API for Google Analytics

1,302 views
Skip to first unread message

Vincent Kleijnendorst

unread,
Apr 25, 2009, 7:46:42 AM4/25/09
to google-analytics-api - GA Data Export API
Hi,

I wrote a PHP API class for the Analytics API.
With the class you can retrieve API data as a PHP array.

See: http://www.swis.nl/ga

carlosT

unread,
Apr 25, 2009, 1:34:31 PM4/25/09
to google-analytics-api - GA Data Export API
Awesome!!! Thank you so much!

clement

unread,
Apr 26, 2009, 6:18:03 PM4/26/09
to google-analytics-api - GA Data Export API
Excellent work.. Thank you for sharing it.

Is the class supporting the secure signing requirements ?

Best regards,
Clement

Vincent Kleijnendorst

unread,
Apr 27, 2009, 3:38:14 AM4/27/09
to google-analytics-api - GA Data Export API
> Is the class supporting the secure signing requirements ?

Hi Clement,

What exactly do you mean by secure signing requirements? The class
retrieves data over SSL (because the API is https).
It uses curl for fetching data.

For authentification it uses ClientLogin (a post with the username and
password to retrieve the 'auth' hash).
http://code.google.com/intl/nl-NL/apis/analytics/docs/gdata/1.0/gdataProtocol.html#ClientLogin

Best regards,

Vincent Kleijnendorst

colorlab

unread,
Apr 27, 2009, 4:23:01 AM4/27/09
to google-analytics-api - GA Data Export API
Hi,

Very nice class Vincent, looks very promising. I tried the demo on
your
server and it went smoothly. Downloading the ga.zip and trying on my
own server failed.

Server is fully capable, it seems to stop when calling the analytics()
function. Credentials are obviously correct.
I am getting a white screen, no errors. Any pointers to fix?

I noticed your SWIS Webbeheer as an ID for the auth source, does this
need to be changed?

Thanks

shecky

unread,
Apr 27, 2009, 4:24:03 AM4/27/09
to google-analytics-api - GA Data Export API
Hi Vincent.
This class is great!!

Only a correction: if in a single account you have more than one
profiles, getProfileList() give same name.
So I change the function. New function is:

[code]
public function getProfileList(){

$sXml = $this->getXml('https://www.google.com/analytics/feeds/
accounts/default');
$aAccounts = $this->parseAccountList($sXml);
$aReturn = array();
foreach($aAccounts as $aAccount){
$aReturn[$aAccount['tableId']] = $aAccount['title'];
}
return $aReturn;
}
[/code]

Sorry for my bad english :-P

Vincent Kleijnendorst

unread,
Apr 27, 2009, 4:46:00 AM4/27/09
to google-analytics-api - GA Data Export API
> I noticed your SWIS Webbeheer as an ID for the auth source, does this
> need to be changed?

Hi,

The ID for the auth source is an identifier for your application. You
can change that to your application. The documentation says: A string
identifying your client application in the form 'companyName-
applicationName-versionID'.

> Server is fully capable, it seems to stop when calling the analytics()
> function. Credentials are obviously correct.
> I am getting a white screen, no errors. Any pointers to fix?

With error_reporting and show_errors you should see the PHP error (if
there is one):

error_reporting(E_ALL);
ini_set("display_errors", 1);

If you can change display_errors in your php.ini file or
with .htaccess you might want to try that too.
Is your server running PHP5.x?

The class throws exceptions in several methods. You can do something
like this:

try {

$oAnalytics = new analytics('[username]', '[password]');
// other code

} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

Vincent Kleijnendorst

unread,
Apr 27, 2009, 4:47:42 AM4/27/09
to google-analytics-api - GA Data Export API
> Only a correction: if in a single account you have more than one
> profiles, getProfileList() give same name.

Thanks for spotting this bug! Your suggested change is changed in the
demo and download.

colorlab

unread,
Apr 27, 2009, 5:18:44 AM4/27/09
to google-analytics-api - GA Data Export API
Thanks for the quick reply. Error reporting is on all the way + PHP
5.x running.

A try and catch resulted in:
Caught exception: Not a valid response (0) url: https://www.google.com/accounts/ClientLogin
http_code 0; doesn't really mean anything to me. Further pointers?

Oh, and I tried several GA accounts (both @gmail.com and other), no
luck either way.

shecky

unread,
Apr 27, 2009, 5:48:35 AM4/27/09
to google-analytics-api - GA Data Export API
Great ;-)

I'm looking to improve this class with more graphics and Ajax call.

Vincent Kleijnendorst

unread,
Apr 27, 2009, 7:13:55 AM4/27/09
to google-analytics-api - GA Data Export API
> A try and catch resulted in:
> Caught exception: Not a valid response (0) url:https://www.google.com/accounts/ClientLogin
> http_code 0; doesn't really mean anything to me. Further pointers?

HTTP code 0 is a bit strange. Is seems that Curl is not working
correctly.

Can you add this after $sOutput = curl_exec($rRequest); in the
class?

if(curl_exec($rRequest) === false){

echo 'Curl error: ' . curl_error($rRequest);
exit;
}

I will put in an extra check for any curl errors in the class later
this day. : )

Vincent Kleijnendorst

unread,
Apr 27, 2009, 7:16:46 AM4/27/09
to google-analytics-api - GA Data Export API
Sorry, correction:

if($sOutput === false){

colorlab

unread,
Apr 27, 2009, 7:24:41 AM4/27/09
to google-analytics-api - GA Data Export API
I did the first and got the error anyway;
Curl error: error setting certificate verify locations: CAfile: /etc/
ssl/certs/ca-certificates.crt CApath: none

Fix is found here; http://chrisschuld.com/2008/07/how-to-fix-the-curl-error-error-setting-certificate-verify-locations/
Add:
curl_setopt($rRequest, CURLOPT_SSL_VERIFYPEER, FALSE);

Although, they suggest fixing the access instead of adding the option.

Baccega Andrea

unread,
Apr 27, 2009, 9:07:38 AM4/27/09
to google-analytics-api - GA Data Export API
Could be useful to add

curl_setopt($rRequest, CURLOPT_SSL_VERIFYHOST, FALSE);

too..



On 27 Apr, 13:24, colorlab wrote:
> I did the first and got the error anyway;
> Curl error: error setting certificate verify locations: CAfile: /etc/
> ssl/certs/ca-certificates.crt CApath: none
>
> Fix is found here;http://chrisschuld.com/2008/07/how-to-fix-the-curl-error-error-settin...

Vincent Kleijnendorst

unread,
Apr 27, 2009, 9:21:46 AM4/27/09
to google-analytics-api - GA Data Export API
> Could be useful to add
>
> curl_setopt($rRequest, CURLOPT_SSL_VERIFYHOST, FALSE);

I disagree. Google is using https for a reason. If you don't check the
host and pear, you might be sending your login credentials to another
site.

jfournaise

unread,
Apr 27, 2009, 12:04:23 PM4/27/09
to google-analytics-api - GA Data Export API
Have a problem with your class.
After login => Curl error: Couldn't resolve host 'www.google.com'

Any idea ?

Vincent Kleijnendorst

unread,
Apr 27, 2009, 1:11:09 PM4/27/09
to google-analytics-api - GA Data Export API
> After login => Curl error: Couldn't resolve host 'www.google.com'
>
> Any idea ?

Seems like a DNS problem. What happens when you try to access the url
with something like wget?

jfournaise

unread,
Apr 28, 2009, 4:29:19 AM4/28/09
to google-analytics-api - GA Data Export API
No problem with wget.
For information i have this error when i try your class on my own
server, no problem with your demo.

Baccega Andrea

unread,
Apr 28, 2009, 4:32:04 AM4/28/09
to google-analytics-api - GA Data Export API
Unfortunately my server ( not mine ) withouth that
CURLOPT_SSL_VERIFYHOST dosn't work.

jfournaise

unread,
Apr 28, 2009, 5:45:10 AM4/28/09
to google-analytics-api - GA Data Export API
Problem fix.
It was simply a problem with curl & ssl.

Very nice class Vincent :)

lacompagniadelcavatappi

unread,
Apr 28, 2009, 11:03:43 AM4/28/09
to google-analytics-api - GA Data Export API
In getData can I use more than 1 dimension and/or metric?

Vincent Kleijnendorst

unread,
Apr 28, 2009, 11:13:10 AM4/28/09
to google-analytics-api - GA Data Export API
> In getData can I use more than 1 dimension and/or metric?

Sure you can : )

print_r($oAnalytics->getData(array( 'dimensions' =>
'ga:keyword,ga:source',
'metrics' =>
'ga:visits',
'sort' =>
'ga:keyword')));

lacompagniadelcavatappi

unread,
Apr 28, 2009, 11:31:57 AM4/28/09
to google-analytics-api - GA Data Export API
I've tried but graph shows only 1 dimension.

Vincent Kleijnendorst

unread,
Apr 28, 2009, 3:27:25 PM4/28/09
to google-analytics-api - GA Data Export API
> I've tried but graph shows only 1 dimension.

The graphs are just there to show an example of what you can do with
the class.
Try a print_r of the result to see what kind of array it returns. You
can then use that array to construct a graph.

I'm using Flash for graphs myself. At the back-end this class is
providing the data.

colorlab

unread,
Apr 28, 2009, 5:01:24 PM4/28/09
to google-analytics-api - GA Data Export API
I would suggest using the Google Charts API to generate graphs of all
sorts. I am looking into it now...

Christian

unread,
May 6, 2009, 8:27:47 AM5/6/09
to google-analytics-api - GA Data Export API
Hi,

first of all: thank you for your class! I'll try to implement a TYPO3
Extension to show google analytics stats in TYPO3 Backend based on
your class. I'll let you know, if it is finished.


I found a bug if you use the class without curl. The problem is, that
file_get_contents() needs another format for 'content' than curl. So
I
added a new line (382) to adapted the $aContext array to work with
file_get_contents:


381 // Curl is not installed, use file_get_contents
382 $sContent = 'accountType='.$sContent
['accountType'].'&Email='.$sContent['Email'].'&Passwd='.$sContent
['Passwd'].'&service='.$sContent['service'].'&source='.$sContent
['source'];
383 // create headers and post
384 $aContext = array('http' => array ( 'method' =>
$sMethod,
385 'header'=> implode
("\r\n", $aHeader) . "\r\n",
386 'content' =>
$sContent));
387 $rContext = stream_context_create($aContext);
388
389 $sOutput = @file_get_contents($sUrl, 0, $rContext);


with this modifications the authentication works for me without curl.


Cheers


Christian



On Apr 25, 1:46 pm, Vincent Kleijnendorst wrote:

Christian

unread,
May 6, 2009, 8:42:25 AM5/6/09
to google-analytics-api - GA Data Export API
there need to be another check, because that function is not used for
auth only:

381 // Curl is not installed, use file_get_contents
382 if (is_array($sContent)) {
383 $sContent = 'accountType='.$sContent
['accountType'].'&Email='.$sContent['Email'].'&Passwd='.$sContent
['Passwd'].'&service='.$sContent['service'].'&source='.$sContent
['source'];
384 }
> > See:http://www.swis.nl/ga- Hide quoted text -
>
> - Show quoted text -

Komweb

unread,
May 25, 2009, 4:15:16 AM5/25/09
to google-analytics-api - GA Data Export API
Hi, I'm getting similar errors when trying to access the page:

Caught exception: Not a valid response () url: https://www.google.com/accounts/ClientLogin

Kommunal.se - Statistik mellan

PHP Notice: Undefined variable: http_response_header in D:\inetpub\test
\ganalytics\analytics.class.php on line 398 PHP Notice: Undefined
variable: http_response_header in D:\inetpub\test\ganalytics
\analytics.class.php on line 400 PHP Notice: Undefined variable:
oAnalytics in D:\inetpub\test\ganalytics\index.php on line 88 PHP
Fatal error: Call to a member function getPageviews() on a non-object
in D:\inetpub\test\ganalytics\index.php on line 88

Any suggestions? I've tried adding the code

if(curl_exec($rRequest) === false){

echo 'Curl error: ' . curl_error($rRequest);
exit;

}

But it made no difference.

- Komweb

On Apr 27, 1:13 pm, Vincent Kleijnendorst wrote:
> > A try and catch resulted in:
> >Caughtexception: Not a valid response (0) url:https://www.google.com/accounts/ClientLogin

Komweb

unread,
May 25, 2009, 5:07:35 AM5/25/09
to google-analytics-api - GA Data Export API
Alright, got closer to fixing this. The first part of the error was
because cURL wasn't turned on.

However, I'm still getting this error message now:

Caught exception: Curl error (couldn't connect to host)

Kommunal.se - Statistik mellan

PHP Warning: Module 'curl' already loaded in Unknown on line 0 PHP
Notice: Undefined variable: oAnalytics in D:\inetpub\test\ganalytics
\index.php on line 88 PHP Fatal error: Call to a member function
getPageviews() on a non-object in D:\inetpub\test\ganalytics\index.php
on line 88

Any help would be appreciated.

- Komweb

mickael44

unread,
May 25, 2009, 10:07:27 AM5/25/09
to google-analytics-api - GA Data Export API
Hi Vincent,

I'm trying to fetch 3 metrics but the result of getData return only
the first metric because the use of $aResult[$sTitle] = $oMetric->item
(0)->getAttribute('value');

I'am doing correction to fetch all metrics :)

Sorry for my english :P

Lily Grace Chao

unread,
Jun 11, 2009, 3:43:50 AM6/11/09
to google-analytics-api - GA Data Export API
Hi!!

I have a client saw your GA API class and gave this to me. I'm new
about this and already confused

I modified first the example.php with the username and password and
profile and I run this in my local and it says

Caught exception: Not a valid response () url: https://www.google.com/accounts/ClientLogin

Another thing is I uploaded this to my server - and I got a different
error. It says "Curl is not supported" - I guess this is already on my
hosting.

Another testing I made is in my company's test server. I run index.php
and after login in - nothing happened - just white.

Please explain to me because I'm not a hardcore PHP programmer.

Any answer will be greatly appreciated.

Thank you

Lily

todda00

unread,
Jul 20, 2009, 7:19:03 PM7/20/09
to google-analytics-api - GA Data Export API
It seems when using this class with a date range, only 30 or 31 dates
can be retrieved because the array is keyed only with the day of the
month. They are also out of order chronologically, and it takes a bit
of data manipulation to get them sorted correctly.

For example if I call this on July 20, 2009:
// set the date range
//-30 days to -1 day
$begin = mktime(0,0,0,date('n'),date('d')-30); //-30 days ago
$end = mktime(0,0,0,date('n'),date('d')-1); //-1 day ago
$oAnalytics->setDateRange(date('Y-m-d',$begin), date('Y-m-d',$end));

It will come back in this order:

July 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,June
20,21,22,23,24,25,26,27,28,29,30

It only sorts them by the lowest day of the month, not by the oldest
day to newest.

If a larger than 30 or 31 (28 for Feb) range is used, only the older
30 or 31 days are retrieved.

Aziz Igam

unread,
Feb 7, 2013, 11:30:55 AM2/7/13
to google-analytics...@googlegroups.com, swi...@gmail.com
Hi Vincent,

Thanks for sharing the great works.
I have applied your code in my current project however I encountered an error as described below, hope you can guide.

Caught exception: Not a valid response (404) url: https://www.google.com/analytics/feeds/accounts/default

In function getXml() in your code, following line led to the error after my investigation:

Could you have a look and let me know what should I do next? 

Regards.
AZ

rushmata

unread,
Aug 25, 2014, 2:46:49 PM8/25/14
to google-analytics...@googlegroups.com, swi...@gmail.com
where is the class?, no class in the link... Can anyone help me? i'm using gapi.class in PHP but it retrieve an Error=BadAuthentication
Reply all
Reply to author
Forward
0 new messages