• Reading time ~ 5 min
  • 18.03.2023

In this article, we'll look at how you can access Google Analytics information in PHP using the API it provides and your service account. We'll use Analytics Reporting Version 4 as the API.

Setting up Google Analytics to work with it using the API

If the site uses Google Analytics (GA) to collect user statistics, then you can use the data provided by this service not only in the web interface through reports, but also through the API.

What does that mean? This means that we can obtain the necessary data from GA programmatically, and then, for example, use it on a website or in a web application.

What tasks can be solved on the site using the Google Analytics API?

  1. Вывести на странице её количество просмотров. Если эту задачу реализовать классическим способом, то нам в этом случае потребуется создавать таблицы в базе данных, писать логику на php и т.д.
  2. Отобразить на сайте самые популярные статьи (страницы) за последнюю неделю или другой период на сайте.

With the help of GA, you can solve not only these tasks on the site, but also many others. But in this article we will focus on the consideration of only these two.

But before moving on to the practical part, first let's look at how to enable the Google Analytics API and the principles of working with it in PHP.

Prepare for the Google API

Before you start working with the fourth version of the Analytics Reporting API, you need to perform the following basic steps:

1. Enable Google Analytics Reporting API.

To do this, you need to open the page "API and Google services".. In the search box, type "Google Analytics Reporting API", go to the page of this API and enable it.

Поиск Google Analytics Reporting API

2. Create a service account.

To do this, you need to open the "Service Accounts" page.

If the project already exists, then click on the "Select" button and select an existing project. If there is no project, then create a new one.

After that, we create a service account in the newly created or selected project. To do this, click on the "Create a service account" button.

Создание сервисного аккаунта в Google IAM

Enter the name of the service account and click on the "Create" button. On the page "Access rights for the service account (optional)" click on the "Continue" button.

Then we create a new key. To do this, click on the "Create Key" button. As a key type, select the value "JSON" and click on the "Create" button. Click on the "Done" button.

The generated key will be downloaded to your computer, we will need it later.

At the end of this step, we will copy the email address of the service account to the clipboard, we will need it to perform the next step.

3. Add a service account to Google Analytics.

To do this, go to Google Analytics and click on the "Administrator" button.

Панель администратора в Google Analytics

After that, in the page that opens, click on "Access Control" in the "Account" section. Then click on the "Plus" icon and select "Add users". Paste the e-mail address of the service account from the clipboard into the opened form and mark only the "View and analyze" option as permissions. Click on the "Add" button.

This user will now have access to analytics through the API.

Installing the Client Library for PHP

The Google API Client Library for PHP can be downloaded manually or obtained using Composer.

For a typical installation, download the archive, unzip it, and upload it to a server, such as the ga.

To install the library using Composer, type the following command:

composer require google/apiclient:^2.0

После установки Google API для PHP загрузите в эту же папку JSON файл, который мы получили на этапе создания сервисного аккаунта.

Secure access to this folder and its file attachments. If you are using an Apache web server, create a file .htaccess in this folder with the following content:

# line below if for Apache 2.4
<ifModule mod_authz_core.c>
    Require all denied
</ifModule>

# line below if for Apache 2.2
<ifModule !mod_authz_core.c>
    deny from all
    Satisfy All
</ifModule>

# section for Apache 2.2 and 2.4
IndexIgnore *

Примеры использования данных из Google Analytics на сайте

Example #1. Using the Google API to get the most popular content on your site.

In this example, let's look at how using the Google Analytics Reporting API you can get the 7 most viewed pages in the last 7 days on the site.

To do this, create a file top_pages.php with the following code:

You can download this file from Github at this link.

In this file you need to specify your data.

First, you need to specify a name for the JSON file that contains the generated key.

$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

Во-вторых, указать значение VIEW_ID.

$VIEW_ID = "";

Узнать значение этого параметра для своей аналитики можно с помощью инструмента Account Explorer.

The ga-dev-tools.appspot.com app must be granted permission to access your Google Account.

In addition, this application has a very good tool for creating queries.

In this example, all the highlights are commented on. You create a query to retrieve data by using an objectreportRequests. The parameters for this query are specified by using objects DateRange, Metrics, Dimensions, OrderBy. Setting these parameters to reportRequests is done by using its special methods.

Example No2. Use the Google API to get the number of views of a particular page on the site.

In this case, we need to install the following in the request:

  • date range (start date, should be equal to the start of your project; end date – the current date);
  • Metric score equal to (number of ga:pageviews views)
  • filter by parameter , the value of ga:pagePathwhich must be equal to the URL of a particular page.

The complete code for the example is available on Github and can be accessed here.

Alternatively, the received data can be uploaded in JSON format to some file (in this example, in /assets/ga_pageviews.json). To do this, you need to write the appropriate function, for example, printResultInFile and use it to process the response.

printResultInFile($response);

Полный код файла доступен на Github по этому адресу.

Then you can write a small script, for example, get_views.php. It will find in the file the number of views for some page knowing its path.

This script will consist of one function:

<?php
function getViews($path) {
  $result = 0;
  $items = json_decode(file_get_contents('ga_pageviews.json'));
  foreach($items as $item) {
      if ($item->{'ga:pagePath'} === $path) {
          $result = $result + (int)$item->{'pageviews'};
      }
  }
  return $result;
}

Теперь чтобы получить данные необходимо просто вызвать функцию getViews и передать ей в качестве параметра путь к странице:

echo getViews('/html-and-css/css-selector');

Что-то подобное можно написать и для первого примера. Т.е. добавить в php-скрипт код, который будет сохранять ответ, а именно 7 самых популярных статей сайта за неделю, в JSON. Далее использовать этот файл для вывода на сайт информационной панели с этими ресурсами. Обновлять файл JSON можно, например, с помощью планировщика cron, запуская php скрипт раз в час или через другое определённое количество времени.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297