Set Up the Google Client Library
- Begin by ensuring you have Composer installed on your system. This will allow you to manage dependencies easily. If not, follow the [official installation guide](https://getcomposer.org/).
- Use Composer to install the Google API client library. Run the following command in your project directory:
composer require google/apiclient
Create a Service Account
- Go to the [Google Cloud Console](https://console.cloud.google.com/) and ensure you are logged into your project.
- Navigate to "IAM & Admin" > "Service accounts" and click "Create Service Account".
- Grant the service account permissions to access your Google Analytics data.
- Create a key (choose JSON format) and store it safely as you will use it in your PHP project.
Prepare the PHP Script
- Initiate your PHP file and include the Composer autoload file to access the Google Libraries:
require_once 'vendor/autoload.php';
- Authenticate and set up a Google Client:
$client = new Google_Client();
$client->setAuthConfig('/path/to/your/service-account-file.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
- Create an authorized Analytics Reporting service object:
$analytics = new Google_Service_Analytics($client);
Query the Google Analytics Reporting API
- Identify the Google Analytics View ID you want to query.
- Using the `Google_Service_Analytics` object, query the API to retrieve data:
$viewId = 'YOUR_VIEW_ID';
$results = $analytics->data_ga->get(
'ga:' . $viewId,
'7daysAgo',
'today',
'ga:sessions,ga:pageviews',
[
'dimensions' => 'ga:date'
]
);
- Process the result to display or utilize it further in your application:
if (count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
printf("Date: %s - Sessions: %d, Pageviews: %d\n", $row[0], $row[1], $row[2]);
}
} else {
print "No results found.\n";
}
Handle Potential Errors
- Consider implementing error handling to capture and log potential issues during API calls. You can wrap API interaction code in try-catch blocks:
try {
$results = $analytics->data_ga->get(
'ga:' . $viewId,
'7daysAgo',
'today',
'ga:sessions,ga:pageviews',
[
'dimensions' => 'ga:date'
]
);
// Process results here
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
Deploying Your Application
- Ensure that your server environment has PHP installed with the necessary extensions (e.g., cURL, JSON).
- Safeguard your service account credentials by not exposing them publicly and restricting file access through server configurations.