コピペで使えるGoogle Analytics APIを使ったオリジナルランキングを作る

2016.9.1

PHP_Logo

PHPをみるだけで吐き気を催す私です。皆様いかがお過ごしでしょうか。

今回はGoogle Analytics APIを利用して、独自のブログランキングを作る方法をお届けします。今回は諸事情があってPHPで書くことになったので、PHPで。コピペですぐ使えます。

前準備

APIに関する事前知識、デベロッパーツールへの登録は既に済んでいるものと仮定します。
PHP のパッケージマネージャ Composerを、ランキング用につかうレンタルサーバーに導入しましょう。フォルダを作って、SSHで移動しておくと良いでしょう。例えばwww直下に、ranking-tool とかでもフォルダを作り、このフォルダにComposerをインストールします。

%curl -sS https://getcomposer.org/installer | php

この一行でインストール完了。
インストールしたフォルダに、composer.jsonを作成します。
以下のコードをテキストで保存します。

{
    "require": {
        "google/apiclient": "1.x"
    }
}

後はインストールコマンドを打ち込んで完了。

$ php composer.phar install

スクリプト本体

ほとんどGoogleさんのサンプルのままですが、コメントアウトを取ればブログカテゴリーのフィルターがかけれます。

<?php
function getService()
{
  // Creates and returns the Analytics service object.

  // Load the Google API PHP Client Library.
  require_once 'vendor/google/apiclient/src/Google/autoload.php';

  // Use the developers console and replace the values with your
  // service account email, and relative location of your key file.
  $service_account_email = '登録したメールアドレス';
  $key_file_location = '.p12ファイルの場所を指定';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("");
  $analytics = new Google_Service_Analytics($client);

  // Read the generated client_secrets.p12 key.
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_email,
      array(Google_Service_Analytics::ANALYTICS_READONLY),
      $key
  );
  $client->setAssertionCredentials($cred);
  if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  return $analytics;
}

function getFirstprofileId(&$analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($properties->getItems()) > 0) {
      $items = $properties->getItems();
      $firstPropertyId = $items[0]->getId();

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        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.');
  }
}


define('ANALYTICS_PROFILE_ID_PROFILE_ID', 'ビューID');
function getWeeklyRanking($analytics){
  $dimensions = 'ga:pageTitle, ga:pagePath' ;
  $results = $analytics->data_ga->get(
    'ga:' . ANALYTICS_PROFILE_ID_PROFILE_ID,
    '7daysAgo',
    'yesterday',
    'ga:pageviews',
    array(
      'dimensions'  => $dimensions,
      'sort'        => '-ga:pageviews',
      'max-results' => '5',
      // フィルター実装する場合 'filters'=>urlencode('ga:pagePath=~/blog'),
    )
  );

  $data = $results->rows;

  foreach ($data as $key => $row) {
    $ranking .='No' . ($key + 1) . '<a href="'. $row[1] . '">' . $row[0] . '</a>' . $row[2] . 'PV';
  }

  return $ranking;
}

$analytics = getService();
$ranking = getWeeklyRanking($analytics);
print_r($ranking);

?>

コピペで使う場合は、IDやp12ファイルなどを適宜書き換えて利用してください。