I'm pretty new to PHP so bear with me please :)
Right so I am working with google analytics and I am using one of their scripts to display one query. It looks all good but I'm not really sure how to display more?
I know to get a query, but I have trouble displaying it. I can only display 1. I only have sessions but I want to add more for example , bounce rate etc.
Here is the code I am using:
<?php
require_once 'google-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('google-client/src/Google/client_secret.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$analytics = new Google_Service_Analytics($client);
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/acp/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstProfileId($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults($analytics, $profileId) {
return $analytics->data_ga->get(
'ga:146790870',
'2016-11-01',
'today',
'ga:sessions');
return $analytics->data_ga->get(
'ga:146790870',
'2016-11-01',
'today',
'ga:percentNewSessions');
}
function printResults($results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$sessionstotal = $rows[0][0];
// Print the results.
print "<div class='col s12 m6 l3' style='text-align:center;'>
<div class='card green '>
<div class='card-content white-text'>
<span class='card-title'>Total Sessions</span>
<p style='font-size: 1.8rem; font-weight: bold;'>$sessionstotal</p>
</div>
<div class='card-action green darken-2'>
</div>
</div>
</div>";
} else {
print "<p>No results found.</p>";
}
}
?>
If someone can give me any tips on how to improve it, or what to do please help me:) Please bear in mind I have very limited knowledge on PHP as I'm learning it while doing projects.
thank you anyway