Analytics API3

<?php
	
	require_once 'vendor/autoload.php';

	$client_id = 'xxxx';

	$view_id = 'xxxx';

	$private_key = @file_get_contents('xxxx');

	$from = date('2017-12-01', strtotime('-1 day'));
	$to = date('2018-01-31');

	$dimensions = 'ga:pageTitle, ga:pagePath, ga:date';
	$metrics = 'ga:pageviews';

	$option = array(
		'dimensions' => $dimensions,
		'max-results' => 10,
		'sort' => '-ga:pageviews',
		'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);

	$obj = $analytics->data_ga->get('ga:'. $view_id, $from, $to, $metrics, $option);

	$json = json_encode($obj);

	$html .= '<h2>実行結果</h2>';
	$html .= '<p><b>' .date('Y/m/d', strtotime($from)). '</b>のページビューのデイリーランキングを取得しました。<mark>値はサンプル用のダミーです。</mark></p>';

	if(!isset($obj->rows))
	{
		$html .= '<p><mark>データを取得できませんでした。</mark></p>';
	}
	else
	{
		$html .= '<ol>';

		for($i=0, $l=count($obj->rows); $l > $i ; $i++)
		{
				$item = $obj->rows[$i];
				$html .= '<li><a href="' . $item&#91;l&#93; .'"target="_blank">' .$item[0]. '<a>(' . number_format($item[3]). 'PV)</li>';		
		}
		$html .= '</ol>';
	}

	$html .= '<h2>取得したデータ(JSON)</h2>';
	$html .= '<textarea row="12">' . $json . '</textarea>';

?>

<?php
		echo $html;
?>