I know how to access Google Analytics data with Data Studio or with Google Apps script in Javascript:
var account = Analytics.Management.Accounts.list().items[0];
var webProperties = Analytics.Management.Webproperties.list(account.id);
...
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
But in PHP, how is it possible to retrieve the number of visitors of a specific website or specific page, from a Google Analytics account / property / view? i.e.:
input: analytics account login/password/website code 'UA-XXXXX-Y'
output: [19873, 17873, 13999, 21032, ..., 16321] (i.e. the number of visits on www.example.com
for each of the 30 last days, as a list of integers or JSON)
Google Analytics (GA) is the standard for measuring website traffic. GA provides an amazing amount of data and is the best way to count website visits for curiosity and to measure results of marketing efforts.
Usually, a unique visitor (or individual user) will be identified by using a unique IP address and any other identifiers like cookies, single user agent, registration ID, etc. It's easy to calculate because you can find this metric on platforms such as Google Analytics, Ahrefs or Alexa.
1. Create <div> container to visitor count using HTML code. The title text is added to HTML file by adding wrapping it in <div></div>. In addition, we need to add another <div></div> with class “website-counter” with empty content for displaying visitor count using JavaScript.
You can use Google Analytics API client in PHP. Google analytic api client library
You can use the Query Explorer to create the queries to check.
Code Example:
$analytics = new analytics('username', 'password');
$analytics->setProfileByName('user.name');
//set the date range for which you want stats for
$analytics->setMonth(date('n'), date('Y'));
// it could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
print_r($analytics->getVisitors());
print_r($analytics->getPageviews());
The above example used the Google Analytics API client in PHP. It was the first library released in PHP. Six years later, this software is outdated. Google changed the API. As an alternative you can use GAPI library. Above is the example how it would work, you can include gapi class to make it functional.
GAPI Analytic Library
Another way is that you can use the Google Analytics Reporting API v4 for PHP. You can obtain this using composer:
composer require google/apiclient:^2.0
Guide to usage of this library is at github
I use this package:
https://github.com/google/google-api-php-client
You can use it to access all the Google APIs from PHP, including of course Google Analytics
Here's an example of how to use it:
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName('Your app name'); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'[email protected]', // email you added to GA
[
'https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('/your/key/file.p12') // keyfile you downloaded
]
)
);
// other settings
$client->setClientId('your-client-id'); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_AnalyticsService($client);
$from_date = date("Y-m-d",strtotime("-30 days")); // A month
$to_date = date("Y-m-d");
$response = $service->data_ga->get(
"ga:profile_id", // profile id
"$from_date", // start date
"$to_date", // end date
"ga:uniquePageviews",
[
'dimensions' => 'ga:pagePath', // Dimensions you want to include, pagePath in this example
'sort' => '-ga:uniquePageviews', // Sort order, order by unique page views from high to low in this case
'filters' => 'ga:pagePath=~\/articles\/[a-zA-Z0-9\-]+', // example url filter
'max-results' => '50' // Max results
]
);
foreach ($response["rows"] as $row) {
// ...do whatever you want with the results
}
Also, here's a guide on how to use the Google APIs:
https://developers.google.com/api-client-library/php/start/get_started
EDIT: You need to create credentials to access the Analytics API. You do it here: https://console.cloud.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key. You need to register a project first, and then create the credentials. There are three options: API key, OAuth client ID and Service Account Key. I didn't want to use OAuth, so I used the Service Account Key. You can try using the API Key, in which case replace the $client->setAssertionCredentials(...)
call for $client->setDeveloperKey(your_api_key)
. You can't use username and password directly AFAIK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With