PHPackages                             mediafigaro/google-analytics-api-symfony - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. mediafigaro/google-analytics-api-symfony

ActiveSymfony-bundle[API Development](/categories/api)

mediafigaro/google-analytics-api-symfony
========================================

Google Analytics API v4 Symfony

1.22(8y ago)46177.7k↓35.7%12[2 issues](https://github.com/mediafigaro/google-analytics-api-symfony/issues)[3 PRs](https://github.com/mediafigaro/google-analytics-api-symfony/pulls)MITPHP

Since Sep 30Pushed 3y ago5 watchersCompare

[ Source](https://github.com/mediafigaro/google-analytics-api-symfony)[ Packagist](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[ Docs](https://github.com/mediafigaro/google-analytics-api-symfony)[ RSS](/packages/mediafigaro-google-analytics-api-symfony/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (7)Used By (0)

Google Analytics API v4 Symfony bundle
======================================

[](#google-analytics-api-v4-symfony-bundle)

[![SensioLabsInsight](https://camo.githubusercontent.com/1e71f7ef6c2a345b3d8cab2eabbf3f94f7ba5fdf81ef66d9909f0a6fd0fd9022/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f64613634323363662d623139382d343032612d386432332d6538326537383333663966362f6269672e706e67)](https://insight.sensiolabs.com/projects/da6423cf-b198-402a-8d23-e82e7833f9f6)

[![Latest Stable Version](https://camo.githubusercontent.com/6188a679d086b9ed5dabb66746f2a92a55a886c436a145cd93d023279054af37/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f762f737461626c65)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![Total Downloads](https://camo.githubusercontent.com/362f91060b51b0d1c26261669e07282e66a7353864d6dc43ff718aa12743a1cd/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f646f776e6c6f616473)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![Latest Unstable Version](https://camo.githubusercontent.com/e17f687a47839dff5f6e6d4cddcd707e89c99fbf3bd374eda50b9924dafabb84/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f762f756e737461626c65)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![License](https://camo.githubusercontent.com/c495cfae91db59064d0d22be291f6228643d0d368280725b77785bf337321dd2/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f6c6963656e7365)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![Monthly Downloads](https://camo.githubusercontent.com/b17295d65b6bf9122254c9db25e623cef99c34a9fab80942f9f0c085d818a585/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f642f6d6f6e74686c79)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![Daily Downloads](https://camo.githubusercontent.com/c8ea0c94e87d613efbc01195c231d8d9b23f41beb8f35797d33b0f1c8f6caa8e/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f642f6461696c79)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)[![composer.lock](https://camo.githubusercontent.com/487fe5d62c05fa8acf3367539d6c96ef2c4cf0b784b84e4219259200431f6c73/68747470733a2f2f706f7365722e707567782e6f72672f6d6564696166696761726f2f676f6f676c652d616e616c79746963732d6170692d73796d666f6e792f636f6d706f7365726c6f636b)](https://packagist.org/packages/mediafigaro/google-analytics-api-symfony)

Use
===

[](#use)

At MEDIA.figaro , the advertising department of the french newspaper Le Figaro and part of the Figaro Group (CCM Benchmark), we use this bundle to monitor our digital platforms with Google Analytics.

It's a simple package that wraps the Google Analytics API version 4, and that gives you all the information to go straight to the point of getting some main metrics from GA.

Development by Kendrick .

To be able to use it, you have to setup a project on Google Console for Google Analytics, get the json key, then configure this package by setting the path for it. You'll have to add the developer email defined into the Google Console to the GA views to authorize it, otherwise the view won't be accessible through the API.

You can use the debug routes to go live and test a profile (ex id : 111111111, here with [Docker](https://github.com/mediafigaro/docker-symfony)) :

[http://symfony.dev/app\_dev.php/analytics-api/111111111](http://symfony.dev/app_dev.php/analytics-api/111111111)

[![debug](doc/debug.png)](doc/debug.png)

Installation
============

[](#installation)

```
composer require mediafigaro/google-analytics-api-symfony

```

without Flex, add to /app/AppKernel.php :

```
$bundles = [
    ...
    new MediaFigaro\GoogleAnalyticsApi\GoogleAnalyticsApi(),
];

```

Versions
========

[](#versions)

1.2
---

[](#12)

Adding filterMetric and filterDimension to getDataDateRangeMetricsDimensions method which is a simple wrapper to Google Api Client ex :

```
$analyticsService = $this->get('google_analytics_api.api');

$data = $analyticsService->getDataDateRangeMetricsDimensions(
    'myanalyticsviewid',    // viewid
    '2018-01-01',   // date start
    'today',        // date end
    ['sessions','users','percentNewSessions','bounceRate'],             // metric
    ['source','campaign','fullReferrer','sourceMedium','pagePath'],     // dimension
    [   // order metric and/or dimension
        'fields'    =>  ['sessions'],
        'order'     =>  'descending'
    ],
    [   // metric
        'metric_name'       =>  'sessions',
        'operator'          =>  'LESS_THAN',
        'comparison_value'  =>  '100'
    ],
    [   // dimension
        'dimension_name'    =>  'sourceMedium',
        'operator'          =>  'EXACT',
        'expressions'       =>  [
            'trading / native'
        ]
    ]
);

```

1.1
---

[](#11)

Symfony 4 simple adaptation with a public service and a new public method that takes in charge metrics and dimensions with sorting options :

```
getDataDateRangeMetricsDimensions($viewId,$dateStart,$dateEnd,$metrics='sessions',$dimensions=null,$sorting=null)

```

Query explorer  to build your query.

$viewId :

$dateStart :

$dateEnd:

$metrics:  (without the 'ga:', array or string)

$dimensions:  (without the 'ga:', array or string)

$sorting:

without the 'ga:', array or string, eg. :

```
[
    'fields'    =>  ['pagePath','sessions'], // or : 'sessions'
    'order'     =>  'descending'
]

```

example :

```
$analyticsService = $this->get('google_analytics_api.api');

$data = $analyticsService->getDataDateRangeMetricsDimensions(
    'myanalyticsviewid',
    '30daysAgo',
    'today',
    ['sessions','users','percentNewSessions','bounceRate'],
    ['source','campaign','fullReferrer','sourceMedium','pagePath'],
    [
        'fields'    =>  ['pagePath','sessions'],
        'order'     =>  'descending'
    ]
)

```

$data :

```
array(329) {
  [0]=>
  array(2) {
    ["metrics"]=>
    array(4) {
      ["sessions"]=>
      string(5) "16738"
      ["users"]=>
      string(5) "15602"
      ["percentNewSessions"]=>
      string(17) "88.39168359421676"
      ["bounceRate"]=>
      string(17) "83.95268251881946"
    }
    ["dimensions"]=>
    array(5) {
      ["source"]=>
      string(7) "trading"
      ["campaign"]=>
      string(7) "my-campaign"
      ["fullReferrer"]=>
      string(7) "trading"
      ["sourceMedium"]=>
      string(16) "trading / native"
      ["pagePath"]=>
      string(50) "/my-url"
    }
  }
  [1]=>
  array(2) {
    ["metrics"]=>
    array(4) {
      ["sessions"]=>
      string(4) "6506"
      ["users"]=>
      string(4) "6200"
      ["percentNewSessions"]=>
      string(17) "87.05810021518599"
      ["bounceRate"]=>
      string(17) "87.74976944359054"
    }
    ["dimensions"]=>
    array(5) {
      ["source"]=>
      string(7) "trading"
      ["campaign"]=>
      string(7) "my-campaign-2"
      ["fullReferrer"]=>
      string(7) "trading"
      ["sourceMedium"]=>
      string(19) "trading / 320x480-1"
      ["pagePath"]=>
      string(50) "/my-url-2"
    }
  }
  [2]=>
  ...

```

**Session - Dimensions &amp; Metrics Explorer** :

1.0
---

[](#10)

First version with a quick connector to consume Google Analytics v4 with Google API client with getDataDateRange private method (that handles only metrics), wrapped with some public methods to get a quick access to main metrics such as sessions (eg. getBounceRateDateRange($viewId,$dateStart,$dateEnd)), bounce rate, average time on page, page view per session, new visits, page views and average page load time. Debug route included for a simple setup and test.

Configuration
=============

[](#configuration)

```
google_analytics_api.google_analytics_json_key

```

Set the relative path for your json key (set it on your server, better not into your repository) from execution path, ex: /data/analytics/analytics-27cef1a4c0fd.json.

/app/config/parameters.yml

```
google_analytics_json_key: "../data/analytics/analytics-27cef1a4c0fd.json"

```

/app/config/config.yml

```
google_analytics_api:
    google_analytics_json_key: "%google_analytics_json_key%"

```

Google API key
==============

[](#google-api-key)

Generate the json file from [https://console.developers.google.com/start/api?id=analyticsreporting.googleapis.com&amp;credential=client\_key](https://console.developers.google.com/start/api?id=analyticsreporting.googleapis.com&credential=client_key) by creating a project, check the documentation : .

Google Analytics API v4
=======================

[](#google-analytics-api-v4)

List of metrics for report building with search engine :  eg. ga:sessions, ga:visits, ga:bounceRate ...

Objects :

(example : ReportData object : )

Samples :

Debug
=====

[](#debug)

Add the debug routes for development purposes :

/app/config/routing\_dev.yml

```
_google_analytics_api:
    resource: "@GoogleAnalyticsApi/Resources/config/routing_dev.yml"

```

[http://symfony.dev/app\_dev.php/analytics-api/000000000](http://symfony.dev/app_dev.php/analytics-api/000000000)

000000000 = profile id that you can find in the analytics URL, p000000000 :

[https://analytics.google.com/analytics/web/?hl=en&amp;pli=1#management/Settings/a222222222w1111111111p000000000/%3Fm.page%3DPropertySettings/](https://analytics.google.com/analytics/web/?hl=en&pli=1#management/Settings/a222222222w1111111111p000000000/%3Fm.page%3DPropertySettings/)

Result of this debug page :

[![debug](doc/debug.png)](doc/debug.png)

Errors
======

[](#errors)

In that 403 error case, follow the link and authorize the API v4.

```
...
    "message": "Google Analytics Reporting API has not been used in project xxxxxx-xxxxxx-000000
    before or it is disabled. Enable it by visiting
    https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=xxxxxx-xxxxxx-000000
    then retry. If you enabled this API recently, wait a few minutes for the action to propagate
    to our systems and retry.",
    "domain": "global",
    "reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"

```

Example
=======

[](#example)

Call the service :

```
$analyticsService = $this->get('google_analytics_api.api');
$analytics = $analyticsService->getAnalytics();

```

Use the method helpers to get the main metrics within a date range :

```
$viewId = '000000000'; // set your view id

// get some metrics (last 30 days, date format is yyyy-mm-dd)
$sessions = $analyticsService->getSessionsDateRange($viewId,'30daysAgo','today');
$bounceRate = $analyticsService->getBounceRateDateRange($viewId,'30daysAgo','today');
$avgTimeOnPage = $analyticsService->getAvgTimeOnPageDateRange($viewId,'30daysAgo','today');
$pageViewsPerSession = $analyticsService->getPageviewsPerSessionDateRange($viewId,'30daysAgo','today');
$percentNewVisits = $analyticsService->getPercentNewVisitsDateRange($viewId,'30daysAgo','today');
$pageViews = $analyticsService->getPageViewsDateRange($viewId,'30daysAgo','today');
$avgPageLoadTime = $analyticsService->getAvgPageLoadTimeDateRange($viewId,'30daysAgo','today');

```

Contribution
============

[](#contribution)

You are welcome to contribute to this small Google Analytics v4 wrapper, to create more helpers or more.

More tools
==========

[](#more-tools)

Try the Symfony Debug Toolbar Git :  and the docker Service Oriented Architecture for Symfony : .

Tutorial
========

[](#tutorial)

French [tutorial](https://www.supinfo.com/articles/single/2423-symfony-27-integration-google-analytics) by Jérémy PERCHE, SUPINFO student.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community16

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 69% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~137 days

Total

5

Last Release

2967d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/10104339f9db32be380a7cfa9be6ead1d01251bc2cfa3def439e6c18349c0b96?d=identicon)[kendrick](/maintainers/kendrick)

![](https://www.gravatar.com/avatar/f49db467f39a98dced4199be6c5f07640bde640710695ae8c6e45b5bdb8a24d1?d=identicon)[mediafigaro](/maintainers/mediafigaro)

---

Top Contributors

[![mediafigaro](https://avatars.githubusercontent.com/u/18629935?v=4)](https://github.com/mediafigaro "mediafigaro (20 commits)")[![kendrick-k](https://avatars.githubusercontent.com/u/4621550?v=4)](https://github.com/kendrick-k "kendrick-k (9 commits)")

---

Tags

analyticsapigooglegoogle-analyticssymfonysymfony-bundleapisymfonygoogleanalyticsv4

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mediafigaro-google-analytics-api-symfony/health.svg)

```
[![Health](https://phpackages.com/badges/mediafigaro-google-analytics-api-symfony/health.svg)](https://phpackages.com/packages/mediafigaro-google-analytics-api-symfony)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[ozankurt/google-analytics

Laravel Google Analytics

7616.7k](/packages/ozankurt-google-analytics)[nanofelis/json-rpc-bundle

This bundle provides a JSON RPC 2.0 implementation for Symfony

1176.1k](/packages/nanofelis-json-rpc-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
