Using Google API to get Google Analytics data with PHP

You might have a need to display data from Google Analytics on your website like number of product page views in your webshop CMS. To achieve that, you would request the page views and maybe sessions (unique visits) for a certain URL from Google Analytics. If you’re using PHP, Google created Google API PHP client to help you do that. In this tutorial we’re going to use Server to Server Application authentication mechanism called two-legged OAuth.

Installing the PHP client

Download code from or, better, use composer and

composer require google/apiclient @stable

Creating a Service Account

Go to Google Developers Console and create a project if you don’t have one for your app. Next, enable the API you want to use, we’re going to use Analytics API in this tutorial. After that, go to Credentials and go and create new Client ID. In the modal, select Service Account. New account will be created and a p12 key file will be downloaded. Store that file in a secure place, readable by your application.

Service account has Client ID and email address: put those in your configuration for future use.

OAuth Service Account

Setting up authorization and Google_Client

To authorize, we’re going to use Google_Auth_AssertionCredentials:

[prism key=”code-authorize” language=”php”]

With this authorization credentials, create the client:

[prism key=”code-client” language=”php”]

Calling Analytics API

First, add that service account email address to analytics account view User Management. Next thing is to request analytics data. We’re going to request pagePath dimension with session and pageviews metrics for a specific analytics view. To get the Analytics View ID, go to analytics account -> Admin -> View settings. Data will be sorted by page views in descending order. We are also going to filter the data by pagePath, as we only want products pages.

[prism key=”code-request” language=”php”]

Your $items array now holds one item, with URL, sessions and page views data. Hope this tutorial helped you, and that you will be able to put various Google Analytics data to good use.

6 Replies to “Using Google API to get Google Analytics data with PHP”

  1. I’ve read many tutorials, but most are outdated. I was able to adapt yours slightly to my own codebase and needs, now it’s working! Thanks for sharing.

  2. Fatal error: Uncaught exception
    ‘GuzzleHttpExceptionRequestException’ with message ‘cURL error 60: SSL
    certificate problem: unable to get local issuer certificate

  3. where to use Google_Auth_AssertionCredentials?? where is the file in which we are going to make changes?

Leave a Reply

Your email address will not be published. Required fields are marked *