debuggable

 
Contact Us
 

New Google Analytics API / DataSource!

Posted on 18/12/07 by Felix Geisendörfer

Hey folks,

sorry it took me forever, but after my old Google Analytics API fell apart due to the fact that Google published a new interface that also came with new reports / exporting formats I didn't have the time to come up with a new one.

Anyway, in a very productive CakePHP session with nate a couple weeks ago in Atlanta I finally implemented some new HttpSocket stuff that was needed (minimal support for cookies / ssl) for creating the new API as a datasource. Now that its done I'm fairly happy with the outcome of the new API : ).

Without further words: Download the 1.0 version here (A SVN:HEAD version of Cake 1.2 is highly recommended).

It doesn't have pretty API comments yet, so I'm gonna make up for it with a little tutorial:

Step 1: Set up your connection credentials

After you downloaded the API and placed it in app/models/datasources/google_analytics_source.php, open up your app/config.database.php and add the following lines:

var $analytics = array(
  'datasource' => 'google_analytics',
  'user' => 'my-account@gmail.com',
  'password' => 'my-password',
);

Naming your connection $analytics is a choice, anything else will do as well.

Step 2: Set up a little test controller:


class AnalyticsController extends AppController{
    var $uses = array();
    var $Analytics = array();

    function beforeFilter() {
        App::import('ConnectionManager');
        $this->Analytics =& ConnectionManager::getDataSource('analytics');
    }

    function list_profiles() {
        // List all profiles associated with your account
        $profiles = $this->Analytics->listSources();
        debug($profiles);
        exit;
    }
   
    function show_reports() {
// The quickest way to test if the API is working for you.
        $report = $this->Analytics->report('Dashboard');
        debug($report);
       
// Use a specific profile id (see list_profiles action above), do:
        $report = $this->Analytics->report(array(
            'profile' => '290723',
            'report' => 'Dashboard'
        ));
        debug($report);

// You can also reference your profile by name instead
        $report = $this->Analytics->report(array(
            'profile' => 'www.thinkingphp.org',
            'report' => 'Dashboard'
        ));
        debug($report);

// Retrieve the raw XML instead of an array to parse it yourself (lets say using SimpleXml in PHP5):
        $report = $this->Analytics->report(array(
            'profile' => 'www.thinkingphp.org',
            'report' => 'Dashboard'
        ), true);
        debug($report);
       
// Retrieve a PDF report (make sure you set the right header before displaying):
        $report = $this->Analytics->report(array(
                'profile' => 'www.thinkingphp.org',
                'report' => 'Dashboard',
                'format' => 'pdf'
            ), true);
        debug($report);

// Set some criteria on the report:
        $report = $this->Analytics->report(array(
                'profile' => 'www.thinkingphp.org',
                'report' => 'Dashboard',
                'from' => '2007-12-17',
                'to' => '2007-12-18'
            ));
        debug($report);
       
/**
 * Small Reference of options:
 *
 * profile: The id or name of the profile (optional, default = first profile)
 * report: A report string like 'Dashboard', 'TrafficSources', 'Keywords' (optional, default = 'Dashboard')
 * from: A yyyy-mm-dd formated date (optional, default = 1 month ago)
 * to: A yyyy-mm-dd formated date (optional, default = today)
 * tab: 0-4 (optional, default = 0)
 * view: 0-9+ (optional, default = 0)
 * format: 0-3 or 'pdf', 'xml', 'csv', 'tsv' (optional, default = 'xml')
 * compute: 'average', other options unknown? (optional, default = 'average')
 * query: Here you can manually pass (and overwrite) any part of the raw HTTP GET query made to Google Analytics. (optional, default = array())
 */

    }
}

Now you might wonder how get the list of reports that are available. Well usually that is pretty simple, just check the name of the menu entry you have open when browsing through the google analytics web interface and try using it in CamelCase. For example the 'Search Engines' view under traffic sources is the same as the 'SearchEngines' report. If this does not work, then use Firebug or something else to find the destination of one of the export links on the screen you are looking at. For example on the 'Direct Traffic' screen (under traffic sources as well), the xml export link points to 'export?fmt=1&id=5879334&pdr=20071116-20071216&cmp=average&&rpt=DirectSourcesReport' which means that the name of the report you need for this API is 'DirectSources'. If I get around I might create some listReports() function, but for now this should do the trick.

Another tip: If you are overwhelmed by the information returned by the default xml reports, try using the CSV / TSV ones, they should usually contain less unneeded information, but you'll have to parse them yourself.

Ok, I hope you guys enjoy and let me know if you have any questions / suggestions / problems.

-- Felix Geisendörfer aka the_undefined

Note: This data source uses web scraping. This means that Google could easily break it by making changes to the infrastructure of Google Analytics again. I also haven't heard back from google about their legal views on this technique since Late May 2006, but so far I haven't heard about Google approaching any vendors providing similar access to their service using web scraping either, which is a good sign.

 
&nsbp;

You can skip to the end and add a comment.

[...] IMPORTANT: The stuff found in this article is outdated and not working anymore. Please see: New Google Analytics API / DataSource! for a newer version! [...]

Lucian Lature  said on Dec 18, 2007:

Nice job!...:)

Pacifists  said on Dec 18, 2007:

Heh the last week I was working on your old API ir remaking it to fit the changes that google introduced, just didn't have time to finish it. I was going to ask you to look at it when I'm finished, but you beat me to it, so I guess all I have to do now - is to use the new one :)

Thanks for the great job. I like the clarity of your code.

oli said on Dec 18, 2007:

coole sache.

Juan Basso said on Dec 18, 2007:

Very nice!

Someone to change in your datasource: You are using "uses('Xml');", replace it by "App::import('Core', 'Xml');". :)

Pacifists  said on Dec 18, 2007:

Juan: I've tried changing that and then 'AppHelper' not found and some other errors poped out. Using SVN cake 1.2, so maybe it's not the best thing to do :)

Matt said on Dec 18, 2007:

Great stuff Felix!

Glad you're back.

Juan Basso said on Dec 18, 2007:

Sorry. I write wrong.

The correct is: App::import('Xml', 'Core');

Snowcore said on Dec 19, 2007:

Thanks for Datasource!
It's really powerful!

PHPDeveloper.org said on Dec 19, 2007:

Felix Geisendorfer's Blog: New Google Analytics API / DataSource!...

Due to the new advancements Google has made in their Analytics ......

[...] Due to the new advancements Google has made in their Analytics API (Datasource) functionality, the API changed slightly and the code that Felix Geisendorfer had created to work with a CakePHP install wasn’t working anymore. He’s corrected the problem with this new post with the new code and an example of its use. In a very productive CakePHP session with nate a couple weeks ago in Atlanta I finally implemented some new HttpSocket stuff that was needed (minimal support for cookies / ssl) for creating the new API as a datasource. Now that its done I’m fairly happy with the outcome of the new API. [...]

[...] Due to the new advancements Google has made in their Analytics API (Datasource) functionality, the API changed slightly and the code that Felix Geisendorfer had created to work with a CakePHP install wasn’t working anymore. He’s corrected the problem with this new post with the new code and an example of its use. In a very productive CakePHP session with nate a couple weeks ago in Atlanta I finally implemented some new HttpSocket stuff that was needed (minimal support for cookies / ssl) for creating the new API as a datasource. Now that its done I’m fairly happy with the outcome of the new API. [...]

[...] Due to the new advancements Google has made in their Analytics API (Datasource) functionality, the API changed slightly and the code that Felix Geisendorfer had created to work with a CakePHP install wasn’t working anymore. He’s corrected the problem with this new post with the new code and an example of its use. In a very productive CakePHP session with nate a couple weeks ago in Atlanta I finally implemented some new HttpSocket stuff that was needed (minimal support for cookies / ssl) for creating the new API as a datasource. Now that its done I’m fairly happy with the outcome of the new API. [...]

Jeanviet said on Dec 22, 2007:

Thanks for the update... still so hard for me to know exactly what i have to do with cake php. can you give us more details (or someone who comments as well)... can you explain all the steps we have to deal with cake php... or maybe just what have changed with the old method (do we need to install cake php 1.2 ? your code works with the old version ?)

[...] http://www.thinkingphp.org/2007/12/18/new-google-analytics-api/ addthis_url = 'http%3A%2F%2Fdavidwalsh.name%2Fgood-web-design-css-working-group-body-id-ie8-acid2-domassistant-25-google-analytics-wii-opera-sdk%2F'; addthis_title = 'Weekend+Links+-+Good+Web+Design%2C+CSS+Working+Group%2C+Body+ID%2C+IE8+Acid2%2C+DOMAssistant+2.5%2C+Google+Analytics%2C+Wii+Opera+SDK'; addthis_pub = ''; [...]

Felix Geisendörfer said on Dec 27, 2007:

Jeanviet: You will need to check out CakePHP 1.2 from SVN and then follow the steps I provided above. Any older cake version will not work. If you have problems with this try to check out the CakePHP mailing list at google groups or hop on freenode IRC #cakephp - there are plenty people who will help you if you ask nice and politely.

But as always, see how much some google research may already help you.

[...] The dashboard is customizable, but the only way to integrate your stats into another product or a centralized dashboard for all your sites is via a web-scrapping API (for CakePHP no less). [...]

jeanviet said on Dec 29, 2007:

Felix: everything is OK now, i put the new version 1.2...

Here you can see my beautiful stats:
http://jeanviet.info/stats/analytics/janusiens

Thanks once again Felix...

Maybe a little question that i was enable to solve.. i'm not an expert in php...

In google analytics datas, you have variables with numbers which are string (7) and not integer...
Example: $pageviews = "154 789"

I would like to change this to integer...

if i do this (int)$pageviews... i've got this: 154

how can i have this: 154789 with a integer variable
i try this (before int function): str_replace (' ', '', $pageviews)

But it doesn't work. the space doesn't disappear.

[...] New Google Analytics API / DataSource! (tags: php) [...]

Jeanviet said on Jan 06, 2008:

Happy new year for those who read the comments... maybe 1 day, i'll have the chance to have an answer to my "spaces" problems in numbers.

Felix Geisendörfer said on Jan 06, 2008:

Jeanviet:

I didn't see any problem with your code, however, I assume this is what happened. Your code looked like this:

str_replace ('', '', $pageviews)
$pageviews = (int)$pageviews;

This does not work b/c str_replace does not work on a reference to the variable you pass in, but on a copy of the value. This means you got to write something like this:

$pageviews = str_replace ('', '', $pageviews);
$pageviews = (int)$pageviews;

or shorter:
$pageviews = (int)str_replace ('', '', $pageviews);

Anyway, its a little inappropriate to ask general PHP questions on here, there are more then enough mailing lists and irc channels full of people to help you with those out there. But no worries, I hope this helps and you're using this API for something fun ; ).

David Lynes  said on Jan 09, 2008:

I am trying to run the same above and have installed as per the instruction but I am getting the following error messages.

Warning (2): preg_split() [function.preg-split]: Compilation failed: lookbehind assertion is not fixed length at offset 9 [CORE/cake/libs/http_socket.php, line 832]

I am using PHP5 with the CakePHP 1.2.0.6311 beta.

Please could anyone help or point me in the right direction please.

Timmy said on Jan 09, 2008:

Nice work. I'm going to test this out today. I was curious though about what/if anything doesn't work if not running off the HEAD 1.2.

Thanks again.

Google Analytics API said on Jan 11, 2008:

[...] Update! A great update to a version that works! Check out the most recent Google Analytics API! Tags:Analytics, API [...]

aleron said on Jan 11, 2008:

great work

santi said on Jan 29, 2008:

hi all could some one show me please some code for the viewer, or some steps to test it, thanks. i think i have it working but havent been able to see any data :S

Suchi  said on Jan 30, 2008:

Hello - I was trying this API out - but am facing with some problems. It seems that the lgin is not working fine for me.
I tried to echo the response we get in the login function - but that forwards me to another login box - with the correct user filled in, no password filled in and a Captcha to be filled in.

When i tried to get the same respone echoed (but now wrapped in htmlentities function) i get the following


Loading... Click here to continue Please click here to continue.



Can you pleae help me out with this.

Suchi  said on Jan 30, 2008:

well - now it seems that the login is working - but still i am not able to get what i want.
When i go to

http://path-to-my-cake/analytics/list_profiles/

I get a lot of warnings etc. and then nothing.

I turned up the debug level and also put in some echos in the listSources function.

When i echoed $response there - i get the login screen of google (naturally the code after that doesnt work ans it is not able to get the matching string)

For more troubleshooting - i echoed $this->connected() & $this->login() and both of them are 1. So why s this asking me to login??

Any idea what can be wrong?

Thank for any help
Suchi

Suchi  said on Jan 30, 2008:

PS: sorry i cant give u the URL of my app - as it is behind htaccess authentication.

Felix Geisendörfer said on Jan 31, 2008:

Suchi: My guess is you are using an old cake version before I added simple cookie support to the HttpSocket.

Suchi Garg  said on Jan 31, 2008:

i downloaded cake_1.2.0.6311-beta.tar.gz and installed that afresh - so it shouldnt be that.

Illundalp said on Feb 05, 2008:
CepOrelpunege said on Feb 07, 2008:

If your different and a bit of a trend setter, not a trend follower, either go with the Licence Plate handbags or design and make your own. ford f 150 air bag light stays on

Shyama Kant  said on Feb 09, 2008:

sir,
For Google Analytics api i have followed the steps written in http://www.thinkingphp.org/2006/06/19/google-analytics-php-api-cakephp-model/ as well as visited this url also http://www.thinkingphp.org/2007/12/18/new-google-analytics-api/

Please let me know which to follow and the required steps to implement the google analytics. Its important.

[...] К сожалению, для Google Analytics нет документированного API, поэтому информацию можно получить только экспериментальным путем или рассматривая соответствующие разработки. Я остановился на втором, за основу были взяты API Джо Тана2 для плагина WordPress Reports3, и Google Analytics API для CakePHP4. Второе не подходит в качестве базового решения, поскольку требует CakePHP знакомиться с которым пока желания нет, да и ставить фреймворк из-за простенького скрипта захочется не всем. В API от Джо я значительно упростил часть работающую непосредственно с GA, убрал лишние запросы и парсинг, которому в элементе отвечающем за загрузку делать нечего. Обратите внимание, что для авторизации требуются логин и пароль Google аккаунта, хранить на хостинге данные основного аккаунта не всегда целесообразно и безопасно, возможно стоит создать аккаунт специально для таких целей и открыть на нем доступ к отчетам сайта. [...]

Cees said on Feb 18, 2008:

How do I download the whole stuff? The downloads on cakeforge.org all seem to point to some "download.php", while in the blog there is spoken of folders like "app/"/

Felix Geisendörfer said on Feb 18, 2008:

Cees: You will need to download CakePHP 1.2 from cakephp.org first before you're going to be able to make any use of this. At this point there is no standalone version of this script.

WyriHaximus said on Feb 23, 2008:

I keep getting this when I try to use this DS " We cannot log you into your account at this time. Please try again later.". Anyone knows how to fix/solve it?

avm  said on Mar 06, 2008:

I'm getting this error

Class 'App' not found in C:\wamp\www\cake\app\controllers\analytics_controller.php on line 22

The line involved is

App::import('ConnectionManager');

What is causing this? Help is appreciated

Felix Geisendörfer said on Mar 06, 2008:

avm: You need to use the latest version of CakePHP 1.2 for this data source to work. You are probably using 1.1.

Jon Peltier said on Apr 12, 2008:

I can't seem to avoid this error.

Fatal error: Class 'GoogleAnalyticsSource' not found in /www/eh7701/public_html/cake_1_2/cake/libs/model/connection_manager.php on line 110

Unfortunately I know little of PHP, though I'm picking it up fast.

Daniel.Interklub said on Apr 15, 2008:

Hi!

Is there new version of method that allows to grab all Top Content section reports?
I need to get about 8000 positions and max passed via query is 500.

Theres no paginationations, so I dont know how to switch to next results.
I'll be very greatful for any suggestions.

DNA

Narendra  said on May 13, 2008:

Help!

My post looks like this (omitted email and pass) and I keep getting just another login page as the response. :-(

HttpSocket Object
(

[description] => HTTP-based DataSource Interface

[quirksMode] =>

[request] => Array

(

[method] => POST

[uri] => Array

(

[scheme] => https

[host] => www.google.com

[port] => 443

[user] =>

[pass] =>

[path] => /accounts/ServiceLoginBoxAuth

[query] => Array

(

)

[fragment] =>
)

[auth] => Array
(

[method] => basic

[user] =>

[pass] =>

)

[version] => 1.1
[body] => continue=http%3A%2F%2Fwww.google.com%2Fanalytics%2Fhome%2F%3Fet%3Dreset%26hl%3Den-US&service=analytics&nui=hidden&hl=en-US&GA3T=ouVrvynQwUs&Email=EEEEEE%40gmail.com&PersistentCookie=yes&Passwd=PPPPPPP

[line] => POST /accounts/ServiceLoginBoxAuth HTTP/1.1

[header] => Host: www.google.com
Connection: close

User-Agent: CakePHP

Content-Type: application/x-www-form-urlencoded

Content-Length: 232

[raw] => POST /accounts/ServiceLoginBoxAuth HTTP/1.1
Host: www.google.com

Connection: close

User-Agent: CakePHP

Content-Type: application/x-www-form-urlencoded

Content-Length: 232

continue=http%3A%2F%2Fwww.google.com%2Fanalytics%2Fhome%2F%3Fet%3Dreset%26hl%3Den-US&service=analytics&nui=hidden&hl=en-US&GA3T=ouVrvynQwUs&Email=EEEEE%40gmail.com&PersistentCookie=yes&Passwd=PPPPPP
[cookies] => Array

(

)

)

[response] => Array
(

[raw] => Array

(

[status-line] =>

[header] =>

[body] =>

[response] =>

)

[status] => Array
(

[http-version] =>

[code] =>

[reason-phrase] =>

)

[header] => Array
(

)

[body] =>
[cookies] => Array

(

)

)

[config] => Array
(

[persistent] =>

[host] => www.google.com

[protocol] => 6

[port] => 443

[timeout] => 30

[request] => Array

(

[uri] => Array

(

[scheme] => https

[host] => www.google.com

[port] => 443

)

[auth] => Array
(

[method] => basic

[user] =>

[pass] =>

)

[cookies] => Array
(

)

)

)

[lineBreak] =>

[_baseConfig] => Array
(

[persistent] =>

[host] => localhost

[protocol] => tcp

[port] => 80

[timeout] => 30

)

[connection] =>
[connected] =>

[error] => Array

(

)

[_log] =>
)

Felix Geisendörfer said on May 13, 2008:

Narendra: Make sure you are using the latest version of CakePHP!

Michael said on May 15, 2008:

Good job! Congratulations.
Thanks for share this app.

TimC  said on May 17, 2008:

Felix - thanks for sharing... One question from a Cake newbie. The API seems to work for me, but instead of a report or something, I get the following messages:

app/controllers/analytics_controller.php (line 29)
Error: The view for AnalyticsController::show_reports() was not found.

Error: Confirm you have created the file: app/views/analytics/show_reports.ctp

I understand what it is looking for, but have no idea what goes into the file!!

Any help appreciated.

Thanks in advance...

Kiyong  said on May 19, 2008:

Thanks~ Felix... :)
I'm Koeran.

You are lucky guy!

I'm happy for you.

Felix Geisendörfer said on May 19, 2008:

TimC: Just create the file and put some text in it. You can also add PHP code to it and output any variables set from your controller using the Controller::set function.

TimC  said on May 26, 2008:

Felix - one more question. I have the ctp file created now, but noticed the debug($report) line in the control file was commented out. When I uncomment the debug($report) line, I get the following:

app/controllers/analytics_controller.php (line 29)

Line 29 is: debug($report);

here is the code in show_reports():

$report = $this->Analytics->report(array(
'profile' => '6723610',

'report' => 'Dashboard'

));

debug($report);

Similar error output occurs for the list_profiles and show_reports. The analytics page in Google has multiple accounts, but the specific id should take care of this (I believe). Just noted the multiple accts as an FYI. Also, running this on a Mac Book Pro w/ Safari and Firefox browsers.

Thanks again in advance...

Tim

TimC  said on May 26, 2008:

Felix - forget my previous request. I just reviewed my database.php file (for like the 10th time) and noticed a typo in my user name that I hadn't noticed before. Arrrghhh, but the good news is, it's working!!

Thanks again!!

Sean Neilan said on May 30, 2008:

I'm getting some kind of SSL error. It says,
Warning (2): fread()function.fread]: SSL: fatal protocol error [CORE/cake/libs/socket.php, line 233

Running PHP 5.2.3 with Zend engine v2.2.0, Zend extension manager v1.2.0 and Zend optimizer v3.2.8

Any ideas?

Thank you very much for your time.

Felix Geisendörfer said on May 30, 2008:

Sean: OS? I know osx can be a tiny bit quirky at times but you should not get this on linux.

Sean Neilan said on May 30, 2008:

@Felix

Thank you for your response!

The PHP script is running server side on a redhat linux box @ hostforweb.com. Although, I'm running OSX here. Normally, I wouldn't think the client side would have much to do with an error like this.

Actually, for some reason, I didn't get this error before and when I showed it to my boss, it came up. Kind of like Michigan J. Frog.

Felix Geisendörfer said on Jun 01, 2008:

Sean: Maybe you need to update your PHP version or SSL bindings. The HttpSocket itself relies on PHPs built-in magic for SSL so I wouldn't really know what could be causing this other then a buggy implementation somewhere down the stack.

narendra said on Jun 18, 2008:

Hi Felix,

I tried a lot with your script, but still i am not getting any output.

its show me below errors

app\controllers\analytics_controller.php (line 21)

app\controllers\analytics_controller.php (line 28)

app\controllers\analytics_controller.php (line 35)

app\controllers\analytics_controller.php (line 42)

app\controllers\analytics_controller.php (line 50)

app\controllers\analytics_controller.php (line 59)

Notice (8): Undefined property: View::$Analytics [APP\controllers\analytics_controller.php, line 20]

Code

function show_reports() {

// The quickest way to test if the API is working for you.

$report = $this->Analytics->report('Dashboard');

AnalyticsController::show_reports() - APP\controllers\analytics_controller.php, line 20
include - APP\views\analytics\show_reports.ctp, line 2

View::_render() - CORE\cake\libs\view\view.php, line 646

View::render() - CORE\cake\libs\view\view.php, line 368

Controller::render() - CORE\cake\libs\controller\controller.php, line 732

Dispatcher::_invoke() - CORE\cake\dispatcher.php, line 260

Dispatcher::dispatch() - CORE\cake\dispatcher.php, line 230

[main] - APP\webroot\index.php, line 84

Fatal error: Call to a member function report() on a non-object in C:\xampp\htdocs\cakephp\app\controllers\analytics_controller.php on line 20

Please help me ,

Thanks

Alex said on Jun 26, 2008:

Great script! Thanks Felix!

Has someone solved the problem of getting the larger datasets(more then 500 records)?

Felix Geisendörfer said on Jun 26, 2008:

Alex: I'll look into it now.

Deepti  said on Jul 10, 2008:

Hi Felix!

You have done a great job with the API. I am facing problems with cakePHP though. I am a new to cakePHP and though I think I have the everything at the right place I do not know how to test it. The only thing I see with show_reports.ctp in place are these lines :

app\controllers\analytics_controller.php (line 21)

app\controllers\analytics_controller.php (line 28)

app\controllers\analytics_controller.php (line 35)

app\controllers\analytics_controller.php (line 42)

app\controllers\analytics_controller.php (line 50)

app\controllers\analytics_controller.php (line 59)

Can you please tell me what and how should I proceed?

Really appreciate your help.

Thanks,
Deepti

Deepti  said on Jul 10, 2008:

Hey it works :) For people facing similar problem please make sure that you have configures your php with ssl. That was my problem.

michaelchan  said on Jul 11, 2008:

I put the API, controller in the location as instructed and have the database and its configuration file up. However, the database is empty.

The CakePHP is up, but how do I proceed from here? How can I show the Analytics result and customize it? Have no any clue at all.

Is there any further sample code or more detail instruction to get it work?

Thanks,
Michael

Patrick  said on Jul 16, 2008:

Has anyone else had any problems with the 'to' 'from' parameters? No matter what, I'm getting exactly one month of data. Even if I do not include those paramaters.

For example:

$report = $this->Analytics->report(array(
'profile' => $id,

'report' => 'PageViews',

'from' => '2008-06-01',

'to' => '2008-06-06',

));

Sam S  said on Jul 25, 2008:

I am getting an error witht the sources var on google_analytics_source.php, line 187

foreach ($sources as $source) {

I can't see why I am getting this, it does not seem to cause adverse effects - I still get data any idea why I get this?

Also things seem to work better with numerical id rather than name passed as profile to the Analytics->report, I guess that not a problem.

Perhaps google is altering the ay analytics work?

its great and would be really positive if google endorsed this (hoping :))

austin_web_developer said on Jul 27, 2008:

I have this all setup but calling
http://mytestapp/analytics/list_profiles

just gives me this
app\controllers\analytics_controller.php (line 14)

I've checked and double checked my login information. I don't have any views included, but I cannot get it to work.
anyone else having the same problem?

austin_web_developer said on Jul 27, 2008:

I just read Deepti's response up above.
I am on a windows box, so I think I might be out of luck.

bummer.

Edmundo  said on Jul 30, 2008:

Hello Felix,

Thank you for your code, it works great!
Do you know if is there a way to get all the links listed on the top content report? I have a site that has 150000+ links on that report and I would like to get that info outside of GA.

Thank you!

Rakesh Muraharishetty said on Aug 05, 2008:

There are a lot of constraints that you need to dig in order to find. I ll better write a small code snippet for you,

http://www.rakesh.ms/blog/2008/08/05/extract-urls-from-google-analytics/

You need to change the profile name(PROFILE_NAME) and number of urls (trows). It is going to take a lot of time for larger websites like yours. Better

Rakesh Muraharishetty said on Aug 05, 2008:

Sorry that my last post was incomplete. I mean better split number of urls into 500 in each go. Google analytics also shows a max of 500 urls per page.

Dirvan  said on Aug 09, 2008:

Hi Felix,

I do not seem to see anything when I run http://localhost:8888/analytics/list_profiles I do not see anything but get this: app/controllers/analytics_controller.php (line 14)

When I use http://localhost:8888/analytics/show_reports I see a chunk of data (with arrays and data) on a yellow background.
Is this is what I should have seen?

I am using the latest Cake version since I have downloaded it today. Its installed under MAMP.

Cheers

Dirvan

Felix Geisendörfer said on Aug 11, 2008:

If you only have one profile you might not get a list, but show reports is expected to dump a bunch of data, yes.

Justin  said on Aug 18, 2008:

I havenever used php cake before, so the instructions above leave me head scratching, how do I run this? When does the code from step 2 go?

satinder  said on Aug 25, 2008:

i have installed everything and ran your analytics api. but got this error mess
Error: Database table googleanalytics for model Googleanalytic was not found.

So i wanted to know what's the structure for that table?

Pattakkaarar  said on Sep 17, 2008:

Hi Deepti,
Im getting the same problem like getting the

app\controllers\analytics_controller.php (line 21)

app\controllers\analytics_controller.php (line 28)

app\controllers\analytics_controller.php (line 35)

app\controllers\analytics_controller.php (line 42)

app\controllers\analytics_controller.php (line 50)

app\controllers\analytics_controller.php (line 59)
in my home page

Could you be more specific about changing 'configures your php with ssl'.

I didnt get that point.

Mandy said on Sep 17, 2008:

Felix,

seems like your code has stopped working for anything other than the default profile. Urls such as https:www.google.comanalyticshomeadminscid have now changed and are returning 302 to settings. Also seems like select box names have also changed.

I am going to take a stab at working with this, but if you get some time or have some insights on this issue, could you please share?

Nick  said on Sep 18, 2008:

Hey Felix,

This was an amazing find, but I too ran into the "302 Moved Temporarily" problem that Mandy has explained above. I will also try to debug this issue and any update would be appreciated.

Thanks!

Mandy said on Sep 19, 2008:

Okay, I have this fixed in my playpen setup. I don't have a public url to post to. Felix, I can email them to you if you want.

Przemek Jazlo  said on Sep 30, 2008:

If you want to retrieve more than standard max. 500 of rows per page, then you need to append extra parameter called 'limit' to your query:

$query = array(
'limit' => 10000, // some big number

);

$report = $this->Analytics->report(array(
'profile' => [your_profile_id],

'report' => [name_of_report],

...

'query' => $query,

));

You can also do more interesting stuff, for example change the default dimension of the report which you want to capture via API. You need to use extra parameter called 'segkey' to specify the dimension:

$query = array(
'segkey' => 'request_uri_1', // changes dimension to 'landing page'

);

// rest is same as above

Please note that GA uses Ajax when changing the dimension. I used Firebug in order to discover parameters in the actual request, since they normally do not appear in the URL of the export link.

I hope the information will be useful to some of you.

-Przemek

knafland said on Oct 07, 2008:

Hello, another CakePHP newcomer. Using /analytics/show_reports/ controller, i get next response:
Array

(

=> Array
        (

            [HEAD] => Array

                (

                    [TITLE] => Array

                        (

                            [#text] => Moved Temporarily

                        )



                )



            [BODY] => Array

                (

                    [H1] => Array

                        (

                            [#text] => Moved Temporarily

                        )



                    [#text] => Array

                        (

                            [0] => The document has moved

                            [1] => .

                        )



                    [A] => Array

                        (

                            [#text] => here

                        )



                )



        )



)

Anny help appreciated!
newbie  said on Oct 07, 2008:

Hi,

I followed all the above steps and when I strat running the script using the below two lines its giving error:
$GA = new AnalyticsController;

$GA->list_profiles();

Error its giving is
[Tue Oct 07 15:20:54 2008] [error] [client 127.0.0.1] PHP Fatal error: Class 'AppController' not found in C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\analytics_controller.php on line 2

Can any body please help me in understanding how to run the test script in Apache...
I have installed CAKE 1.2 version only.

newbie  said on Oct 08, 2008:

Hi,

I am able to configure cake php and other stuff but giving other errors.
Can any body please help me in solving my problem:

app\controllers\analytics_controller.php (line 14)

which was reported by people earlier... but could not see any solution for this.... any help on configuring php with ssl would help me...

Thanks...

Christ0ph said on Oct 16, 2008:

is there any way to get for example data from analytics/reporting/content_detail_navigation?

Ive tried to use the "Reports" parametre, but that doesnt work. Im also abit unsure how i could use the query parametre for this. Anyone?

Mike said on Nov 07, 2008:

Can this be incorporated into Wordpress?

ss_convert  said on Nov 11, 2008:

Thanks for taking time to write this code Felix. I had to make the following changes to my google_analytics_source.php to get everything working:

1) Changed "https://www.google.com/analytics/home/..." to "https://www.google.com/analytics/settings/..." everywhere

2) Line 105: Changed "account_list" to "scid"

3) Line 123: Changed "profile_list" to "id"

To everyone getting started, it really helps if you change your debug level to 3 on Line 43 of core.php. This allows you to see the Controller Dump. If you read down through it you can usually see where things are failing.

Jo   said on Dec 11, 2008:

hi,
while running analytics/show_reports , i have received the following error

Array

(

=> Array
        (

            [HEAD] => Array

                (

                    [TITLE] => Array

                        (

                            [#text] => Moved Temporarily

                        )



                )



            [BODY] => Array

                (

                    [H1] => Array

                        (

                            [#text] => Moved Temporarily

                        )



                    [#text] => Array

                        (

                            [0] =>

The document has moved

                            [1] => .



                        )



                    [A] => Array

                        (

                            [#text] => here

                        )



                )



        )



)





appreciated your help
JP  said on Dec 24, 2008:

I managed to get some things working by using the comment of ss_convert, and replacing /cake/libs/http_socket.php @ line 848 with: $parts = preg_split('/(< ![^;]")?;[ \t]*/', $cookie);

JP  said on Dec 24, 2008:

$parts = preg_split('/(>![^;]")?;[ \t]*/', $cookie);

JP  said on Dec 24, 2008:

finally, this is the correct one:
$parts = preg_split('/(<![^;]")?;[ \t]*/', $cookie);

JP  said on Dec 24, 2008:

You also wanna replace the url around line 121 in the google_analytics_source.php with:

/settings/?scid=

(instead of some thing with /admin)

Arnout  said on Feb 11, 2009:

Do you also have a standalone version of this? :-)
I think lots of people can use this as a standalone app as well.

austin_web_developer said on Feb 18, 2009:

I've made the edits suggested above and posted the updated file here
http://github.com/concept47/cake-php-google-analytics/tree/master

I hope you don't mind Felix, I haven't figured out how to send patches yet. Once I do, I'll send the patch over. If you integrate the changes, let me know, so I can take the repo down.

austin_web_developer said on Feb 18, 2009:

If you're on a windows box and are getting the errors above where nothing is outputting at the debug calls, Your problem is that you don't have open ssl support installed.

The HttpSocket Component that Felix uses, eventually makes a call using fsockopen or pfsockopen. If the connection is a secure one, it tries to do this over ssl:// instead of https://.

To install openssl, just go here
http://us3.php.net/manual/en/openssl.installation.php

But basically, all you need to do is uncomment this line in your php ini

;extension=php_openssl.dll

Martijn Duizendstra said on Mar 05, 2009:

I'm sorry, i just can't get this thing to work. I've updated the google_analytics_source.php file according to Austin_web_developer's changes but i still keep getting the damn errors on every line where a debug is occuring. I've tested CURL, OpenSSL, fsockopen, pfsockopen and everything is working, phpinfo() is also showing me that OpenSSL is installed and enabled. I hope someone can help me with this problem, or else i just have to pray that Google will release their API soon... Thanks in advance

austin_web_developer said on Mar 05, 2009:

Post your errors, and your php version plus os.

Martijn Duizendstra said on Mar 05, 2009:

Hey thanks for replying so fast man.
I'm running Windows 2003 Server Web Edition, PHP Version 4.4.3

When i go to: index.php?url=/analytics/list_profiles

It shows me this error:
app\controllers\analytics_controller.php (line 18)

If i go to: index.php?url=/analytics/show_reports it will show:
app\controllers\analytics_controller.php (line 24)

app\controllers\analytics_controller.php (line 31)

app\controllers\analytics_controller.php (line 38)

app\controllers\analytics_controller.php (line 45)

app\controllers\analytics_controller.php (line 53)

app\controllers\analytics_controller.php (line 62)

and:
Error: The view for analyticsController::show_reports() was not found.

But the view shouldn't be the problem of the error right?
Thanks in advance

Martijn Duizendstra said on Mar 10, 2009:

Anyone?

austin_web_developer said on Mar 10, 2009:

To be specific ... your problem would be in the file
cake/libs/socket.php

problem is that the connect function is connecting over ssl:// in line 109
using fsockopen in line 114

do some good old debugging (echo 'hello'; exit;)
So see where the script is dying ... if it is dying after that fsockopen call, then you haven't fixed your ssl problem (which is what I think your problem might be).

Martijn Duizendstra said on Mar 11, 2009:

Hey thanks for you reply. The thing i don't understand is where the "debug()" command is coming from. Is it a default cake function, or do i need to install something into the framework for this?

In the meanwhile I will check the things you've said. Let me know, thanks in advance.

austin_web_developer said on Mar 11, 2009:

yes. It is a cakephp function.
It is what is outputting thing like

app\controllers\analytics_controller.php (line 24)

It should be followed by some data, but in your case the data is blank.

Martijn Duizendstra said on Mar 11, 2009:

Cake is showing the same type of notice/error when i run this function as well... maybe it's another issue?

function index() {
debug("Test");

}

if i run the url /index.php?url=/analytics/index it executes the index() function, and shows "Test" as output, but the notice/error is also showing

app\controllers\analytics_controller.php (line 11)

What am i doing wrong here...

austin_web_developer said on Mar 11, 2009:

You don't seem familiar with cakephp ...
that is what it is supposed to do.

carlos  said on Apr 16, 2009:

I am a newbie. I have uploaded cakePHP to my server into a folder called cake. I have uploaded the api into cake/app/models/datasources directory. Now where do I put the test code shown above??? I tried to put it in a file cake/analytics.php but i get a red and yellow error screen which says...

Error: Analytics.phpController could not be found.

Error: Create the class Analytics.phpController below in file: app/controllers/analytics.php_controller.php

< ?php
class Analytics.phpController extends AppController {

var $name = 'Analytics.php';
}

?>

I tried creating app/controllers/analytics.php_controller.php as suggested and it didn't change anything.

Please a little step by step guide would be so useful for noobs like me.

Alan Blount said on Apr 22, 2009:

There's a new official google API to get data:

http://code.google.com/apis/analytics/docs/gdata/1.0/gdataProtocol.html#ClientLogin

Anyone want to volunteer to create a new data source? (yes, I know I should step up to this challenge, but my one year old disagrees)

thanks,
-alan-

Nathan Dunlap  said on Jun 01, 2009:

Great to see this. Having an issue though...

When I enable the Auth component in the app_contorller, I recieve the following error...

Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/pow3/app/models/datasources/google_analytics_source.php:254) [CORE/cake/libs/controller/controller.php, line 640]

Ideas???

Benson  said on Jun 15, 2009:

Am new to cakephp. Please give a sample view that i can use to display the reports on my website.

Martijn Duizendstra said on Jun 15, 2009:

Hi Benson,

The datasource described above can be considered obsolete because the official Google Analytics Data Export API is now available to all developers outside the private beta program.

You can read more here: http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataDeveloperGuide.html

Good Luck!

Benson  said on Jun 15, 2009:

Hi Martijn Duizendstra

Thanks for the quick response. I will have a look at the API and I hope It will be helpful.

Fred Ballard  said on Oct 26, 2009:

Sadly, in light of the new Google Analytics API and ga:pi(), and this no longer working, isn't it time to retire this?

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.