I have a GA4 account and propertyId created, I have created the service account and got the JSON file also.
I am implementing a code in which I want to get the Google Analytics data for my PHP application.
I have added the composer and also the package:
"google/apiclient": "^2.14",
This is the code i am trying to get the data.
// Create a Google Analytics service object.
$analytics = new Google_Service_AnalyticsReporting(
[
'credentials' => file_get_contents('client_secrets.json'),
]
);
// Create a request object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
// Set the property ID.
$request->setPropertyId('YOUR_PROPERTY_ID');
// Set the dimensions and metrics that you want to get.
$request->setDimensions(['ga:pagePath', 'ga:visits']);
$request->setMetrics(['ga:users', 'ga:bounceRate']);
// Call the Google Analytics API.
$response = $analytics->reports()->batchGet($request);
// Get the results.
foreach ($response->getReports() as $report) {
foreach ($report->getData() as $row) {
// Print the results.
echo $row->getDimensions()[0] . ': ' . $row->getMetrics()[0]->getValue() . PHP_EOL;
}
}
But in this line:
$request->setPropertyId('YOUR_PROPERTY_ID');
I get the error
Error
Call to undefined method GoogleServiceAnalyticsReportingReportRequest::setPropertyId()
I am doing this first time, so also please help me if I am not on the correct path.