Hey there, fellow developer! Ready to dive into the world of Google Analytics API integration? We'll be using the google/analytics-data
package to make our lives easier. This guide assumes you're already familiar with PHP and have some context about APIs. Let's get cracking!
Before we jump in, make sure you've got:
If you're missing any of these, take a quick detour to set them up. Trust me, it'll save you headaches later!
First things first, let's get that google/analytics-data
package installed. Fire up your terminal and run:
composer require google/analytics-data
Easy peasy, right?
Now for the fun part - authentication:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/key-file.json"
Pro tip: Add this to your .bashrc
or .zshrc
to make it permanent.
Let's get our hands dirty with some code:
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; $client = new BetaAnalyticsDataClient(); $propertyId = 'YOUR_GA4_PROPERTY_ID';
Replace YOUR_GA4_PROPERTY_ID
with your actual GA4 property ID. You know the drill!
Time to fetch some data:
$response = $client->runReport([ 'property' => 'properties/' . $propertyId, 'dateRanges' => [ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]), ], 'metrics' => [ new Metric(['name' => 'activeUsers']), ], ]); foreach ($response->getRows() as $row) { echo $row->getMetricValues()[0]->getValue() . "\n"; }
Boom! You've just pulled your active users for the last 7 days.
Want to flex those API muscles? Try these:
'dateRanges' => [ new DateRange([ 'start_date' => '2023-01-01', 'end_date' => '2023-12-31', ]), ],
'metrics' => [ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'sessions']), ], 'dimensions' => [ new Dimension(['name' => 'country']), ],
'dimensionFilter' => new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'country', 'string_filter' => new StringFilter([ 'value' => 'United States', ]), ]), ]), 'orderBys' => [ new OrderBy([ 'metric' => new MetricOrderBy(['metric_name' => 'activeUsers']), 'desc' => true, ]), ],
Don't forget to wrap your API calls in try-catch blocks:
try { $response = $client->runReport([/* ... */]); } catch (ApiException $e) { echo 'Oops! ' . $e->getMessage(); }
Common errors? Check your credentials, property ID, and API quotas.
To keep things speedy:
And there you have it! You're now equipped to harness the power of Google Analytics data in your PHP applications. Remember, the API is vast, so don't be afraid to explore and experiment.
For more in-depth info, check out the official documentation.
Now go forth and analyze!
Here's a complete script to get you started:
<?php require 'vendor/autoload.php'; use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\Dimension; $client = new BetaAnalyticsDataClient(); $propertyId = 'YOUR_GA4_PROPERTY_ID'; try { $response = $client->runReport([ 'property' => 'properties/' . $propertyId, 'dateRanges' => [ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]), ], 'metrics' => [ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'sessions']), ], 'dimensions' => [ new Dimension(['name' => 'country']), ], ]); foreach ($response->getRows() as $row) { echo $row->getDimensionValues()[0]->getValue() . ': '; echo 'Active Users: ' . $row->getMetricValues()[0]->getValue() . ', '; echo 'Sessions: ' . $row->getMetricValues()[1]->getValue() . "\n"; } } catch (ApiException $e) { echo 'Oops! ' . $e->getMessage(); }
Happy coding!