LoginSignup
41
43

More than 5 years have passed since last update.

[PHP]Google Analytics API v3.0 使い方〜データ取得編

Last updated at Posted at 2013-06-16

今回はいよいよGoogleAnalyticsからデータを取得する処理です。

5月にPV数が多かった日付を降順に10件取得してみます。

Client IDの作成方法は[PHP]Google Analytics API v3.0 使い方〜前準備編を御覧ください。
アカウント認証処理については[PHP]Google Analytics API v3.0 使い方〜認証編を御覧ください。

■ ディレクトリ構成
前回同様以下の様に配置しています
/www
 /lib
  /google-api-php-client・・・ダウンロードしてきたライブラリ
 signin.php
 index.php

■ index.phpにGoogleAnalyticsからデータを取得する処理を追加

index.php
<?php
require('lib/google-api-php-client/src/Google_Client.php');
require('lib/google-api-php-client/src/contrib/Google_AnalyticsService.php');

session_start();
$client = new Google_Client();

// クライアントID
$client->setClientId('Your Client ID');
// クライアントSecret
$client->setClientSecret('Your Client Secret');
// リダイレクトURL
$client->setRedirectUri('http://example/index.php');

// 使用するサービスを作成
$service = new Google_AnalyticsService($client);

// トークンセット
$client->setAccessToken($_SESSION['token']);

// 以下4つは必須項目
$profile_id = 'ga:123456789'; // プロファイルID
$start_date = '2013-05-01'; // 開始日付(YYYY-MM-DD)
$end_date = '2013-05-31'; // 終了日付(YYYY-MM-DD)
$metrics = 'ga:visits'; // 取得する指標(複数指定する場合は「,」でつなげる

// その他指定する場合は連想配列にまとめる
$optParams = array(
        'dimensions'=> 'ga:date', // ディメンション(複数指定する場合は「,」でつなげる
        'sort' => '-ga:visits', // 何でソートするか(降順の場合は先頭に「-」をつける
        'max-results' => 10,// 取得する最大件数
);

$data = $service->data_ga->get($profile_id, $start_date, $end_date, $metrics, $optParams);
$list = array();
foreach ($data['rows'] as $row => $value) {
    $result = array();
    foreach ($data['columnHeaders'] as $key => $header) {
        $result[$header['name']] = $value[$key];
    }
    $list[] = $result;
}
?>

<table class="table table-bordered table-striped">
    <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>

Bootstrap, from Twitter (4).png

41
43
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
41
43