2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでGoogle Analytics APIを使ったオリジナルランキングを作る

Posted at

Google Analytics APIのサンプルに少しの付け足しでランキングを作るやつです。Google Analytics APIそのものの、利用準備は割愛します。Google Developer Consoleでやってください。

前準備

とりあえずレンタルサーバーでの運用の場合。今回はさくらのレンタルサーバーを使います。
PHP のパッケージマネージャ Composerを使うのが楽です。圧倒的です。

SSHで該当ディレクトリへ移動し、以下のコマンドを入力します。

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

終わり。

次にcomposer.jsonを作成します。
以下のコードをテキストで保存します

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

後はインストールコマンドを入力。

$ php composer.phar install

準備は完了のはずです。

サンプルスクリプト

ほぼGoogle提供のスクリプトのまんまですね。

sample.php

<?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);

?>


sample.phpを叩くと、ランキングが表示されます。簡単。

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?