Retrieve Google Analytics Visits and PageViews with PHP
Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? Anyways I check my website statistics more often than I should and it ends up taking a few minutes to get logged in, select the right site, select the current day, etc. I found a great Google Analytics PHP API that allows me to get just the statistics I'm looking for.
The PHP Library
The PHP class I found, analytics, can be downloaded at http://www.swis.nl/ga/. The site also gives a few solid examples.
//session_start for caching, if desired session_start(); //get the class require 'ga/analytics.class.php'; //sign in and grab profile $analytics = new analytics('email@example.com', 'myP@ssw0rd'); $analytics->setProfileByName('davidwalsh.name'); //set the date range for which I want stats for (could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD')) $analytics->setMonth(date('n'), date('Y')); //get array of visitors by day print_r($analytics->getVisitors()); //get array of pageviews by day print_r($analytics->getPageviews());
As you'd expect, we first grab the class and immediately sign providing your credentials and website profile (you can just use your domain). Once authenticated we set a date range and retrieve our visitors and pageviews.
The Sample PHP Results
The above code retrieved visits and pageviews for the current month. What's returned is an array that looks as follows:
Array (  => 6539  => 6677  => 6160  => 5563  => 2964  => 2973  => 5080  => 6078  => 5927  => 6177 ... )
A very simple array numbered by day. You could do anything you wanted with the array -- create averages, peaks, lows, etc.
The analytics class also allows you to retrieve search keywords and anything else you might like:
$keywords = $analytics->getData(array( 'dimensions' => 'ga:keyword', 'metrics' => 'ga:visits', 'sort' => 'ga:keyword' ) );
The PHP analytics class is a masterpiece. Rest assured I'll be doing a ton of work with this class for customers and my own websites! Do you have any ideas as to what you could use this class for? Share!