How to Fetch Reports from Google Analytics API Using PHP
If you're running a website, tracking user interactions is crucial to understanding what works and what needs improvement. Google Analytics provides powerful insights, and the best part is you can automate report fetching using the Google Analytics API with PHP. In this article, we will walk through the complete process of fetching reports using PHP, including authentication, API requests, and outputting results. This guide is SEO-optimized and perfect for developers looking to streamline their analytics workflow.
Prerequisites
Before you start, ensure the following:
* A Google Cloud Platform (GCP) project with Google Analytics API enabled.
* Service Account credentials (JSON file).
* Access to the Google Analytics 4 (GA4) property.
* Composer installed on your local development machine.
* A basic understanding of PHP.
Step 1: Install Google Client Library via Composer
Open your terminal and navigate to your project directory. Then run:
composer require google/apiclient
This will install the Google API PHP client.
Step 2: Create a Service Account and Download Credentials
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Navigate to APIs & Services > Credentials.
- Click Create Credentials > Service account.
- After creation, go to the service account and click Add Key > JSON.
- Save the downloaded JSON key file to your project directory.
- Share your GA4 property with the service account email (e.g.,
your-service-account@your-project.iam.gserviceaccount.com
) as a Viewer or Analyst.
Step 3: Set Up PHP Script to Authenticate and Fetch Report
Create a file called fetch_report.php
and include the following code:
require_once 'vendor/autoload.php';
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
$propertyId = 'YOUR-GA4-PROPERTY-ID';
$keyFilePath = 'path/to/your/service-account.json';
putenv("GOOGLE_APPLICATION_CREDENTIALS=$keyFilePath");
$client = new BetaAnalyticsDataClient();
$response = $client->runReport([
'property' => "properties/$propertyId",
'dateRanges' => [
new DateRange([
'start_date' => '2023-01-01',
'end_date' => '2023-12-31',
]),
],
'dimensions' => [
new Dimension(['name' => 'city']),
],
'metrics' => [
new Metric(['name' => 'activeUsers']),
],
]);
// Output the results
foreach ($response->getRows() as $row) {
echo 'City: ' . $row->getDimensionValues()[0]->getValue() . PHP_EOL;
echo 'Active Users: ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
echo str_repeat('-', 20) . PHP_EOL;
}
Replace YOUR-GA4-PROPERTY-ID
and the JSON path with your actual values.
Step 4: Run the Script
In the terminal, run:
php fetch_report.php
You should see a list of cities and the number of active users in each.
Conclusion
Fetching reports from the Google Analytics API using PHP is a great way to automate analytics workflows and integrate data into custom dashboards or applications. With the steps above, you can easily authenticate with a service account and query the Analytics Data API for various metrics and dimensions.