Extract data from google analytic with PHP
My PHP class to extract data from Google Analytics API to show on your own website.
Using:
- PHP
- cURL to connect to Google Analytics Data Extract API
- PHP DOMDocument to parse XML
- Google Graph API to show analytic data
Screenshot:
How to use?
Download full source code here -> GAAPI
Construct and use the class
Include class file and call to construct with params username, password and site id(from url in google analytic account “id=xxxxxxxx”)
include_once('gaapi.class.php');
$ga=new gaApi('google username','google password','ga:site id');
//e.g. ('myname@gmail.com','myPassword','ga:1234567');
Site ID in Google Analytic URL
Generate Report
This require knowledge of Dimension and Metric from Google Analytic Data Extract API. Basically it is to combine between Dimensions and Metrics to generate reports through method genReport(array). For examples.
$params = array ('metrics' => 'ga:visits',
'dimensions' => 'ga:source',
'start-date' => '2010-01-01',
'end-date' => '2010-02-09',
'max-results' => '5',
'filter' => 'ga:source != (direct)',
'sort' => '-ga:visits');
$result=$ga->genReport($params);
print_r($result);
The result will be collection of array like this.
Array
(
[0] => Array
(
[ga:source] => google
[ga:visits] => 5029
)
[1] => Array
(
[ga:source] => xxxxxxx.com
[ga:visits] => 162
)
[2] => Array
(
[ga:source] => search
[ga:visits] => 49
)
)
Also there’s some pre-made method of frequency use statistic in my class such as:
$now=date("Y-m-d");
$lastmonth=date('Y-m-d', strtotime('-30 days'));
//Summery: visitors, unique visit, pageview, time on site, new visits, bounce rates
$summery=$ga->getSummery($lastmonth,$now);
//All time summery: visitors, page views
$allTimeSummery=$ga->getAllTimeSummery();
//Last 10 days visitors (for graph)
$visits=$ga->getVisits($lastmonth,$now,10);
//Top 10 search engine keywords
$topKeywords=$ga->getTopKeyword($lastmonth,$now,10);
//Top 10 visitor countries
$topCountries=$ga->getTopCountry($lastmonth,$now,10);
//Top 10 page views
$topPages=$ga->getTopPage($lastmonth,$now,10);
//Top 10 referrer websites
$topReferrer=$ga->getTopReferrer($lastmonth,$now,10);
//Top 10 visitor browsers
$topBrowsers=$ga->getTopBrowser($lastmonth,$now,10);
//Top 10 visitor operating systems
$topOs=$ga->getTopOs($lastmonth,$now,10);
Each method generate collection of array with dimension and metric name as key
Download the code here -> GAAPI
Please let me know if you find any bugs!


ขอบคุณมากครับ ข้อมูลที่ได้เป็นประโยชน์มากครับ