Search code examples
phpgoogle-analyticsgoogle-analytics-api

Filter Google Analytics API using URL


We have a couple views in Google Analytics that we generate reports for through their API. These views are working fine for us right now in terms of getting either the number of users or sessions. However, on one of the views, we'd like to drill down to specific pages.

For example we'd like to know the number of users that visited my-page.php from July 2021 to August 2021.

This is my current code:

// Create and configure a new client object
$client = new Google_Client();
$client->setApplicationName("Analytics");
$client->setAuthConfig(__ROOT__ . '/analytics/client_secrets.json');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

$analytics = new Google_Service_AnalyticsReporting($client);

// Create DateRange objects.
$july = new Google_Service_AnalyticsReporting_DateRange();
$july->setStartDate("2021-07-01");
$july->setEndDate("2021-07-31");

$august = new Google_Service_AnalyticsReporting_DateRange();
$august->setStartDate("2021-08-01");
$august->setEndDate("2021-08-31");

// Create the Metrics object.
$metric = new Google_Service_AnalyticsReporting_Metric();
$metric->setExpression("ga:users");
$metric->setAlias("users");

//Create the Dimensions object.
$dimension = new Google_Service_AnalyticsReporting_Dimension();
$dimension->setName("ga:pagePath");

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges(array($july, $august));
$request->setDimensions(array($dimension));
$request->setMetrics(array($metric));

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));

$reports = $analytics->reports->batchGet($body);

for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
        $row = $rows[ $rowIndex ];
        $dimensions = $row->getDimensions();
        $metrics = $row->getMetrics();
        for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
            print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "<br>");
        }

        for ($j = 0; $j < count($metrics); $j++) {
            $values = $metrics[$j]->getValues();
            for ($k = 0; $k < count($values); $k++) {
                $entry = $metricHeaders[$k];
                print($entry->getName() . ": " . $values[$k] . "<br>");
            }
        }
    }
}

You'll notice that I am using ga:pagePath but I'm not sure if I'm going at this the right direction because it's giving me all pages visited during those two months and I see no way of filtering it by just the page I want to see.

If it helps, this is what my code gives as a result:

...
ga:pagePath: /some/path/other-page.php
users: 388
users: 208
ga:pagePath: /some/path/my-page.php        <------ I want this
users: 417
users: 376
ga:pagePath: /wrong/path/wrong-page.php
users: 128
users: 87
...

I'd like to mention that we are able to do something similar from the Google Analytics front-end by going to:

Behavior > Site Content > All Pages

And then search for my-page.php. This is what I want to replicate through the API.


Solution

  • You have to create a Dimension Filter. You can find an example in official documentation: https://developers.google.com/analytics/devguides/reporting/core/v4/samples#php_4

    Something like this:

    $dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
    $dimensionFilter->setDimensionName("ga:pagePath");
    $dimensionFilter->setOperator('REGEXP');
    $dimensionFilter->setExpressions('my-page.php');
    $dimensionFilter->setNot(TRUE);