<?php
require_once 'vendor/autoload.php';
$client_id = '';
$view_id = '';
$private_key = @file_get_contents('');
$from = date('Y-m-d', strtotime('-1 month'));
$to = date('Y-m-d');
$dimensions = 'ga:date';
$metrics = 'ga:visits';
$option = array(
'dimensions' => $dimensions,
'max-results' => 10,
'sort' => '-ga:visits',
'start-index' => 11,
);
if(isset($_SESSION['service_token']))
{
$client->setAccessToken($_SESSION['service_token']);
}
$scopes = array('https://www.googleapis.com/auth/analytics.readonly');
$credentials = new Google_Auth_AssertionCredentials($client_id, $scopes, $private_key);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
$_SESSION['service_token'] = $client->getAccessToken();
$analytics = new Google_Service_Analytics($client);
$data = $analytics->data_ga->get('ga:'. $view_id, $from, $to, $metrics, $option);
$list = array();
foreach($data['rows'] as $row => $value){
$result = array();
foreach($data['columnHeaders'] as $key => $header){
$result[$header['name']] = $value[$key];
}
$list[] = $result;
}
?>
<table>
<thead>
<tr>
<th>pagepath</th>
<th>visits</th>
</tr>
</thead>
<tbody>
<?php
foreach($list as $val){
echo "<tr>";
foreach ($val as $data){
echo "<td>$data</td>";
}
echo "</tr>";
}
?>
</tbody>
</table>