1. First, mostly follow the steps from the API Quickstart Guide found at the url below

https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries#php

While logged into the associated Google account, click on the button, ‘Enable the Google Analytics Data API v1’.

Enter a name for your project, then download and save the JSON file provided upon success. Add this file to your project in a non web accessible location.

2. Get the Property ID for the Analytics property you are connecting with

Navigate to the Admin panel of your Analytics account. Click on ‘Property Settings’ in the menu options. From there, the Property ID is visible.

3. Add the service account as a User in Analytics

Open the JSON key file provided previously and look for “client_email” key. Copy the email address that follows.

Add this email address as a user in your Analytics account. This is the user managed service account we will be using for authentication. In this scenario, the role only needs to be ‘Viewer.’

4. Update code

Replace the values indicated in the code and run your code. The dimensions and metrics shown below will pull relative page urls and their views in the specified date range.

Other available options can be found in Google’s documentation:

https://developers.google.com/analytics/devguides/reporting/data/v1/exploration-api-schema

require 'vendor/autoload.php';

use Google\Cloud\Core\ServiceBuilder;
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;

// Path to JSON key file
const PATH_TO_GOO_CREDS = '/the/path/to/json/G4-Data-API-Test-xxxxxxxxx.json';

/**
 * Replace this variable with your Google Analytics 4
 *   property ID
 */
$property_id = 'xxxxxxxxxxx';

$config = [
    'credentials' => PATH_TO_GOO_CREDS,
];

$client = new BetaAnalyticsDataClient($config);

// Make call to Data API
$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2023-01-01',
            'end_date' => 'today',
        ]),
    ],
    'dimensions' => [new Dimension(
        [
            'name' => 'pagePath',
        ]
    ),
    ],
    'metrics' => [new Metric(
        [
            'name' => 'screenPageViews',
        ]
    )
    ]
]);

// Display Results from API call
print 'Analytics Data: ' . PHP_EOL;

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

Leave a comment

Your email address will not be published.