To extract data from the Google Analytics API using PHP, you’ll need to follow a series of steps. This involves setting up a project in the Google Cloud Console, enabling the Google Analytics API, creating credentials, and then writing PHP code to make API requests. Here’s a step-by-step guide:
- Set up a Google Cloud Project:
- Go to the Google Cloud Console (https://console.cloud.google.com/).
- Create a new project or select an existing one.
2.Enable the Google Analytics API:
- In the Google Cloud Console, navigate to the “APIs & Services” > “Dashboard.”
- Click on “+ ENABLE APIS AND SERVICES.”
- Search for “Google Analytics API” and enable it for your project.
3. Create API Credentials:
- In the Google Cloud Console, navigate to “APIs & Services” > “Credentials.”
- Click on “+ CREATE CREDENTIALS” and choose “Service Account Key.”
- Fill out the required information and grant the necessary permissions for your service account.
- Download the JSON key file for your service account, which will be used for authentication in your PHP code.
4. Share Google Analytics Access:
- In the Google Analytics account you want to access, grant read access to the email address associated with your service account’s JSON key.
5. Install Required PHP Libraries:
You’ll need to install the required PHP libraries to interact with the Google Analytics API. You can use Composer to manage your project’s dependencies.
composer require google/apiclient
- Write PHP Code to Extract Data:
Here’s a basic example of PHP code to extract data from the Google Analytics API using thegoogle/apiclient
library:
<?php
require 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('path/to/your-service-account-key.json');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
$profileId = 'ga:YOUR_PROFILE_ID';
$startDate = '2023-01-01';
$endDate = '2023-01-31';
$results = $analytics->data_ga->get(
$profileId,
$startDate,
$endDate,
'ga:pageviews'
);
$rows = $results->getRows();
foreach ($rows as $row) {
// Process the data
echo "Pageviews: " . $row[0] . "\n";
}
Make sure to replace 'path/to/your-service-account-key.json'
with the path to your downloaded JSON key file and 'YOUR_PROFILE_ID'
with your Google Analytics profile ID. You can customize the metrics and dimensions you want to retrieve by modifying the ga:pageviews
parameter.
- Run Your PHP Script:
Run your PHP script, and it should fetch data from the Google Analytics API and display it as per your code.
Remember that this is just a basic example, and you can expand on it to retrieve more data and perform various operations with the Google Analytics API using PHP. Be sure to handle authentication securely and follow best practices when working with API keys and secrets.