PHPackages                             spatie/analytics-statistics - 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. spatie/analytics-statistics

ActiveLibrary[API Development](/categories/api)

spatie/analytics-statistics
===========================

An opinionated php package to retrieve Google Analytics data.

1.0.1(10y ago)794.8k11MITPHPPHP &gt;=5.3.0

Since Jun 1Pushed 3mo ago7 watchersCompare

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

READMEChangelog (1)Dependencies (5)Versions (4)Used By (0)

Analytics Statistics: Retrieve data from Google Analytics
=========================================================

[](#analytics-statistics-retrieve-data-from-google-analytics)

[![Latest Version](https://camo.githubusercontent.com/41715ed24d45c1b2ceaa554dd22d3e70778e8f442387cf48a298bf1c0796b6bf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7370617469652f616e616c79746963732d737461746973746963732e7376673f7374796c653d666c61742d737175617265)](https://github.com/spatie/analytics-statistics/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/858d23c093ed119dc801e64ba88cef65be951af293a31576e46cc3fb25b770d7/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f616e616c79746963732d737461746973746963732f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/analytics-statistics)[![Quality Score](https://camo.githubusercontent.com/d65d332f16832c5ec2906ecb70eccb2b2d167b612468b2d07d59084fa9fb6ee4/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f616e616c79746963732d737461746973746963732e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/analytics-statistics)[![Total Downloads](https://camo.githubusercontent.com/f42ff38b56edba695ac84850cd350031e7d510dc2e71c6592df748c0816dceb1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f616e616c79746963732d737461746973746963732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/analytics-statistics)

An opinionated package to retrieve Google Analytics data. Compatible with PHP &gt;= 5.3.

If you're using laravel 5, check out our [laravel-analytics](https://github.com/spatie/laravel-analytics/) package!

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/12b227d7dbe230e07fc46b9bdf27013ee44fe86ba3041c7d53b21bbc73577270/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f616e616c79746963732d737461746973746963732e6a70673f743d31)](https://spatie.be/github-ad-click/analytics-statistics)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Postcardware
------------

[](#postcardware)

You're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment you are required to send us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

The best postcards will get published on the open source page on our website.

Install
-------

[](#install)

This package can be installed through Composer.

```
composer require spatie/analytics-statistics
```

### How to obtain the credentials to communicate with Google Analytics

[](#how-to-obtain-the-credentials-to-communicate-with-google-analytics)

If you haven't already done so, [set up a Google Analytics property](https://support.google.com/analytics/answer/1042508) and [install the tracking code on your site](https://support.google.com/analytics/answer/1008080?hl=en#GA).

This package needs valid configuration values for `siteId`, `clientId` and `serviceEmail`. Additionally a `p12-file`is required.

To obtain these credentials start by going to the [Google Developers Console](https://console.developers.google.com).

If you don't have a project present in the console yet, create one. If you click on the project name, you'll see a menu item `APIs` under `APIs & auth` on the left hand side. Click it to go the the Enabled API's screen. On that screen you should enable the Analytics API. Now, again under the `APIs & Auth`-menu click `Credentials`. On this screen you should press `Create new Client ID`. In the creation screen make sure you select application type `Service Account` and key type `P12-key`.

This wil generate a new public/private key pair and the .p12-file will get downloaded to your machine. Store this file in the location specified in the configfile of this package.

In the properties of the newly created Service Account you'll find the values for the `serviceEmail` and `clientId` listed as `CLIENT ID` and `EMAIL ADDRESS`.

To find the right value for `siteId` log in to [Google Analytics](http://www.google.be/intl/en/analytics/) go the the Admin section. In the property-column select the website name of which you want to retrieve data, then click `View Settings` in the `View`-column. The value presented as `View Id` prepended with 'ga:' can be used as `siteId`.

Make sure you've added the `ANALYTICS_SERVICE_EMAIL` to the Google Analytics Account otherwise you will get a `403: User does not have any Google Analytics Account` error. [You can read Google's instructions here](http://support.google.com/analytics/bin/answer.py?hl=en&answer=1009702).

If you want to use the realtime methods you should [request access](https://docs.google.com/forms/d/1qfRFysCikpgCMGqgF3yXdUyQW4xAlLyjKuOoOEFN2Uw/viewform) to the beta version of [Google's Real Time Reporting API](https://developers.google.com/analytics/devguides/reporting/realtime/v3/).

Usage
-----

[](#usage)

### Setup

[](#setup)

The easiest way to set up Analytics is via the factory method `\Spatie\Analytics\Analytics::create()`. The `create` method requires the following parameters:

```
/**
 * @param  string $siteId
 * @param  string $clientId
 * @param  string $serviceEmail
 * @param  string $certificatePath
 */
```

You can optionally add some extra parameters to set up caching:

```
/**
 * @param  \Spatie\Analytics\Cache $cache
 * @param  int $cacheLifetimeInMinutes
 * @param  int $realTimeCacheLifetime
 */
```

*Note: If you want to use a cache, you'll need to write your own implementation/adapter using the `\Spatie\Analytics\Analytics\Cache` interface.*

#### Example

[](#example)

```
use Spatie\Analytics\Analytics;

$analytics = Analytics::create(
    'ga:xxxxxxxx',
    'xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
    'xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com',
    '/keys/analytics/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12',
    $myCache,
    60 * 24 * 2,
    5
);
```

When the setup is done you can easily retrieve Analytics data. Methods generally return a plain array.

Here is an example to retrieve visitors and pageview data for the last seven days.

```
/*
* $analyticsData now contains an array with 3 columns: "date", "visitors" and "pageViews"
*/
$analyticsData = $analytics->getVisitorsAndPageViews(7);
```

Here's another example to get the 20 most visited pages of the last 365 days

```
/*
* $analyticsData now contains an array with 2 columns: "url" and "pageViews"
*/
$analyticsData = $analytics->getMostVisitedPages(365, 20);
```

Provided methods
----------------

[](#provided-methods)

### Visitors and pageviews

[](#visitors-and-pageviews)

These methods return an array with columns "date", "vistors" and "pageViews". When grouping by yearMonth, the first column will be called "yearMonth".

```
/**
 * Get the amount of visitors and pageviews
 *
 * @param  int $numberOfDays
 * @param  string $groupBy Possible values: date, yearMonth
 * @return array
 */
public function getVisitorsAndPageViews($numberOfDays = 365, $groupBy = 'date')

/**
 * Get the amount of visitors and pageviews for the given period
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  string $groupBy  Possible values: date, yearMonth
 * @return array
 */
public function getVisitorsAndPageViewsForPeriod($startDate, $endDate, $groupBy = 'date')
```

### Keywords

[](#keywords)

These methods return an array with columns "keyword" and "sessions".

```
   /**
 * Get the top keywords
 *
 * @param  int $numberOfDays
 * @param  int $maxResults
 * @return array
 */
public function getTopKeywords($numberOfDays = 365, $maxResults = 30)

/**
 * Get the top keywords for the given period
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  int $maxResults
 * @return array
 */
public function getTopKeyWordsForPeriod($startDate, $endDate, $maxResults = 30)
```

### Referrers

[](#referrers)

These methods return an array with columns "url" and "pageViews".

```
/**
 * Get the top referrers
 *
 * @param  int $numberOfDays
 * @param  int $maxResults
 * @return array
 */
public function getTopReferrers($numberOfDays = 365, $maxResults = 20)

/**
 * Get the top referrers for the given period
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  $maxResults
 * @return array
 */
public function getTopReferrersForPeriod($startDate, $endDate, $maxResults)
```

### Browsers

[](#browsers)

These methods return an array with columns "browser" and "sessions".

If there are more used browsers than the number specified in maxResults, then a new resultrow with browser-name "other" will be appended with a sum of all the remaining browsers.

```
/**
 * Get the top browsers
 *
 * @param  int $numberOfDays
 * @param  int $maxResults
 * @return array
 */
public function getTopBrowsers($numberOfDays = 365, $maxResults = 6)

/**
 * Get the top browsers for the given period
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  $maxResults
 * @return array
 */
public function getTopBrowsersForPeriod($startDate, $endDate, $maxResults)
```

### Most visited pages

[](#most-visited-pages)

These methods return an array with columns "url" and "pageViews".

```
/**
 * Get the most visited pages
 *
 * @param  int $numberOfDays
 * @param  int $maxResults
 * @return array
 */
public function getMostVisitedPages($numberOfDays = 365, $maxResults = 20)

/**
 * Get the most visited pages for the given period
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  int $maxResults
 * @return array
 */
public function getMostVisitedPagesForPeriod($startDate, $endDate, $maxResults = 20)
```

### Currently active visitors

[](#currently-active-visitors)

This method uses the [Real Time Reporting API](https://developers.google.com/analytics/devguides/reporting/realtime/v3/). It returns the amount of visitors that is viewing your site right now.

```
/**
 * Get the number of active users currently on the site
 *
 * @param  array $others
 * @return array
 */
public function getActiveUsers($others = array())
```

### All other Google Analytics Queries

[](#all-other-google-analytics-queries)

To perform all other GA queries use `performQuery`. [Google's Core Reporting API](https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries) provides more information on on which metrics and dimensions might be used.

```
/**
 * Call the query method on the autenthicated client
 *
 * @param  \DateTime $startDate
 * @param  \DateTime $endDate
 * @param  $metrics
 * @param  array $others
 * @return mixed
 */
public function performQuery($startDate, $endDate, $metrics, $others = array())
```

Testing
-------

[](#testing)

Run the tests with:

```
vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [Matthias De Winter](https://github.com/MatthiasDeWinter)
- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [All Contributors](../../contributors)

About Spatie
------------

[](#about-spatie)

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance54

Moderate activity, may be stable

Popularity32

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~0 days

Total

2

Last Release

4003d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (6 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (4 commits)")

---

Tags

spatiegoogle-analytics

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-analytics-statistics/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-analytics-statistics/health.svg)](https://phpackages.com/packages/spatie-analytics-statistics)
```

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[spatie/laravel-fractal

An easy to use Fractal integration for Laravel applications

1.9k15.1M99](/packages/spatie-laravel-fractal)[spatie/laravel-route-attributes

Auto register routes using PHP attributes

879963.2k18](/packages/spatie-laravel-route-attributes)[spatie/fractalistic

A developer friendly wrapper around Fractal

38715.3M8](/packages/spatie-fractalistic)[spatie/laravel-json-api-paginate

A paginator that plays nice with the JSON API spec

6314.7M46](/packages/spatie-laravel-json-api-paginate)[spatie/dropbox-api

A minimal implementation of Dropbox API v2

3116.0M36](/packages/spatie-dropbox-api)

PHPackages © 2026

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