By Sam Deering

Display Traffic Stats From Google Analytics API

By Sam Deering

This is how you can use Google Analytics API to get traffic statistics for your website. My original aim was to get live stats and display them on the blog… but as far as I am aware Google Analytics API doesn’t support real-time stats yet… but this is still useful if you want to display pageviews or number of visits on your site and have it automatically update.

In this post

  • Setup your Google Analytics API Access
  • Frontend JavaScript to call backend script and display data
  • Backend PHP Script to connect to Google Analytics API
  • Live Working Demo
  • Download Package for you to try it yourself



Setup your Google Analytics API Access

This is fairly straight forward and should only take 2 minutes. Go to

Activate analytics api for your project.

Create a new oAuth 2.0 client (click the big blue button…)

Make sure the Google Analytics Service is switched on.

Your screen should now look something like this:

The Frontend Script

This script basically makes an ajax request to the backend script and then parses the JSON data to create the graphs.

    Author: Sam Deering 2012
    Licence: MIT.


        //loading image for ajax request
        var $loading = $('#galoading');
            start: function()
            complete: function()

        $.getJSON('data.php', function(data)
            // console.log(data);
            if (data)

                //raw data

                //mini graph
                var miniGraphData = new Array();
                $.each(data, function(i,v)
                     miniGraphData.push([v["visits"], v["pageviews"]]);
                // console.log(miniGraphData);
                $('#minigraph').sparkline(miniGraphData, { type: 'bar' });

                //get graph data
                var xAxisLabels = new Array(),
                    dPageviews = new Array(),
                    dVisits = new Array();
                $.each(data, function(i,v)

                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'graph',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    title: {
                        text: 'jQuery4u Blog Traffic Stats',
                        x: -20 //center
                    subtitle: {
                        text: 'Source: Google Analytics API',
                        x: -20
                    xAxis: {
                        categories: xAxisLabels
                    yAxis: {
                        title: {
                            text: 'Pageviews'
                        plotLines: [{
                            value: 0,
                            width: 5,
                            color: '#FF4A0B'
                    tooltip: {
                        formatter: function() {
                                return ''+ +'
'+ this.x +': '+ this.y.toString().replace(/B(?=(d{3})+(?!d))/g, ",") +' pageviews'; } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 }, series: [ { name: 'pageviews', data: dPageviews }, { name: 'visits', data: dVisits }] }); } else { $('#results').html('error?!?!').show(); } }); }); })(jQuery);

The Backend PHP Script

This script connects to Google Analytics API and grabs the data associated with your project (website).

setAccessType('online'); // default: offline
$client->setApplicationName('[INSERT YOUR APP NAME HERE]');
$client->setClientId('[INSERT YOUR KEY HERE]');
$client->setClientSecret('[INSERT YOUR KEY HERE]');
$client->setDeveloperKey('[INSERT YOUR KEY HERE]'); // API key

// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);

if (isset($_GET['logout'])) { // logout: destroy token
    die('Logged out.');

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $_SESSION['token'] = $client->getAccessToken();

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);

try {

    //specific project
    $projectId = '[INSERT PROJECT ID HERE]'; //see here for how to get your project id:

    // metrics
    $_params[] = 'date';
    $_params[] = 'date_year';
    $_params[] = 'date_month';
    $_params[] = 'date_day';
    // dimensions
    $_params[] = 'visits';
    $_params[] = 'pageviews';

    //for more metrics see here:

    // $from = date('Y-m-d', time()-2*24*60*60); // 2 days ago
    // $to = date('Y-m-d'); // today
    $from = date('Y-m-d', time()-7*24*60*60); // 7 days ago
    $to = date('Y-m-d', time()-24*60*60); // 1 days ago

    $metrics = 'ga:visits,ga:pageviews,ga:bounces,ga:entranceBounceRate,ga:visitBounceRate,ga:avgTimeOnSite';
    $dimensions = 'ga:date,ga:year,ga:month,ga:day';
    $data = $service->data_ga->get('ga:'.$projectId, $from, $to, $metrics, array('dimensions' => $dimensions));

    $retData = array();
    foreach($data['rows'] as $row)
       $dataRow = array();
       foreach($_params as $colNr => $column)
           $dataRow[$column] = $row[$colNr];
       array_push($retData, $dataRow);
    // var_dump($retData);
    echo json_encode($retData);

} catch (Exception $e) {
    die('An error occured: ' . $e->getMessage()."n");

The script in debug:


View Live Demo
View Data Access
You’ll need permission to view the demo. I’ll hook up a public demo soon.


Download Source Files from GitHub

  • subbu

    very nice great !!!!

  • Anil Kumar

    good one!!!

  • Brian

    I did all the steps but is Not working :/

    • Did you download package from GitHub? You’ll need to input your API keys in the backend PHP script.

  • Lughino

    The live demo is not working!

    • Isn’t working for me too.

      • Sorry the live demo doesn’t work because of permissions. It works only when I am logged in! So if you login to your account and run the source code it should work.

        • anonymous

          How can others see the stats then???

    • prompter


  • Tom

    How should I change data.php and the javascript so it can show more than one chart on one page?

    • Tom

      BTW: I did change the script so it also works with a Google Analytics API service account. That’s great when you don’t want the user to approve access. Of course you still need to add a developer user to the google analytics account of the user.

    • Tom

      Never mind. Solved.

  • NotMyName

    Does not work…

  • Guest

    not working dear i mention my all details in data.php but it give error like

  • Ed Rooney

    Is there a method for setting sort order or filters using this script?

  • Nick Spiel

    Great tutorial. ONe thing to note is that in the new API the line foreach($data[‘rows’] as $row) needs to be foreach($data->rows as $row)

  • Ramesh Tiwari

    really very very nice.

    But please help me i don’t need to login everytime on google account and access need to verify.

    Actually i want display all my google analytical data in my custom admin panel.
    But when i logout from the google analytical or access token expire it’s again need to recall data.php file.

    I realy need you help. Please reply me on my other email id really wating…

  • OzanKurt96


Get the latest in JavaScript, once a week, for free.