How to implement Google Analytics API using PHP
Accessing Google Analytics Data with PHP
Google Analytics provides a wealth of data about your website's performance, including information about user behavior, traffic sources, and more. You can access this data programmatically using the Google Analytics API. In this guide, we'll walk you through the process of setting up a PHP script to authenticate with Google Analytics and fetch data from your account.
Prerequisites
Step 1: Set Up a Google Cloud Project and Enable the Analytics API
- Go to the Google Cloud Console.
- Create a new project or use an existing one.
- Enable the "Google Analytics API" for your project.
Step 2: Create OAuth 2.0 Credentials
- In the Google Cloud Console, navigate to "APIs & Services" > "Credentials."
- Click on "Create credentials" and select "OAuth client ID."
- Choose the application type as "Web application."
- Add your authorized redirect URIs. For local development, you can use something like http://localhost/oauth2callback.php.
- After creating the credentials, note down the Client ID and Client Secret.
Step 3: Install Required Libraries
You'll need to use the Google API PHP client library. You can install it using Composer:
composer require google/apiclient:^2.0
Step 4: Setting Up the PHP Script
We'll start by creating a PHP script that initializes the Google Analytics API, retrieves the first profile ID, fetches data, and prints the results. Here's the complete script:
<?php require __DIR__ . '/vendor/autoload.php'; // Replace with your own credentials $clientId = 'YOUR_CLIENT_ID'; $clientSecret = 'YOUR_CLIENT_SECRET'; $redirectUri = 'http://localhost/oauth2callback.php'; $client = new Google_Client(); $client->setAuthConfig([ 'web' => [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'redirect_uris' => [$redirectUri], ], ]); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // Initialize the Analytics service $analytics = new Google_Service_Analytics($client); if (!isset($_GET['code'])) { $authUrl = $client->createAuthUrl(); header('Location: ' . $authUrl); die(); } else { $client->fetchAccessTokenWithAuthCode($_GET['code']); $accessToken = $client->getAccessToken(); // Store the access token securely // Initialize Analytics function initializeAnalytics($analytics) { // Get the list of accounts $accounts = $analytics->management_accounts->listManagementAccounts(); if (count($accounts->getItems()) > 0) { $firstAccountId = $accounts->getItems()[0]->getId(); // Get the list of properties for the first account $properties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0) { $firstPropertyId = $properties->getItems()[0]->getId(); // Get the list of views (profiles) for the first property $profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstPropertyId); if (count($profiles->getItems()) > 0) { return $profiles->getItems()[0]->getId(); } } } return null; } function getResults($analytics, $profileId) { // Use the Analytics service object to get data return $analytics->data_ga->get( 'ga:' . $profileId, '30daysAgo', // Start date 'today', // End date 'ga:sessions' // Metric(s) to retrieve ); } function printResults($results) { if (count($results->getRows()) > 0) { $rows = $results->getRows(); foreach ($rows as $row) { echo "Sessions: " . $row[0] . "<br>"; } } else { echo "No data found<br>"; } } // Get the first profile ID $profileId = initializeAnalytics($analytics); if ($profileId) { // Get and print the results $results = getResults($analytics, $profileId); printResults($results); } else { echo "No profiles found for this user."; } } ?>
Note
- Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the credentials you obtained from the Google Cloud Console.
- Run the script on your web server. Access the script in your browser (e.g., http://localhost/your-script.php).
- Follow the OAuth2 authorization flow to grant access to your Google Analytics data.
- Once authorized, the script will fetch and display the number of sessions for the selected Google Analytics profile.
With this script, you can retrieve and use various Google Analytics metrics and dimensions according to your needs. It serves as a foundation for building more advanced analytics and reporting tools with PHP.