アクセス解析にGoogle Analyticsを導入しているサイトであれば、
Google提供のライブラリを使用して、ログ情報の取得が可能です。

まず、GAPIを下記サイトより GAPIをダウンロードしてください。
https://code.google.com/p/gapi-google-analytics-php-interface/
簡単なアクセスランキングのサンプルコード
サンプルコードでは、ログイン情報とビューIDを適時書き換えてください。
define( ‘GA_E_MAIL’, ‘xxxxxx@gmail.com’ );
define( ‘GA_PASSWORD’, ‘xxxxxxxxxxx’ );
define( ‘GA_PROFILE_ID’, ‘1234567’ );
<?php
//GAPI読み込み
require_once( 'gapi.class.php' );
//キャッシュ処理
function getCacheFile($idFunc = "") {
//キャッシュ時間
$cacheTime = 24*60*60;
$cacheFile = "./cache/".$idFunc; // キャッシュファイルの場所
if(!function_exists($idFunc)) {
return;
}
if(file_exists($cacheFile)) {
$time = filemtime($cacheFile);
if(($time + $cacheTime)>time()) {
return unserialize(file_get_contents($cacheFile));
}
}
$body = call_user_func($idFunc);
$file = new SplFileObject($cacheFile, "w"); // PHP5以上
$file->fwrite(serialize($body));
return $body;
}
//アナリティクス取得設定
function getGoogleAnalytics(){
//ログイン情報
define( 'GA_E_MAIL', 'XXXXXXXX@gmail.com' );
define( 'GA_PASSWORD', 'XXXXXXXXXXX' );
//ビューID
define( 'GA_PROFILE_ID', '1234567' );
//ディメンション
$dimensions = array('hostname','pageTitle','pagePath');
//指標
$metrics = array('pageviews','visits');
//結果のソート順と方向
$sort_metric = '-pageviews';
//フィルター
$filter="pagePath =~ ^/";
//取得期間
$start = date( 'Y-m-d', strtotime( '-1 day' ));
$end = date( 'Y-m-d', strtotime( '-1 day' ));
//開始インデックス
$start_index=1;
//結果フィードの最大取得数
$max_results = 10;
try{
$ga = new gapi( GA_E_MAIL, GA_PASSWORD );
} catch(Exception $e){
return false;
}
if(!empty($ga)){
$ga->requestReportData(
GA_PROFILE_ID,
$dimensions,
$metrics,
$sort_metric,
$filter,
$start,
$end,
$start_index,
$max_results
);
return $ga->getResults();
}
}
//viewエリア
$ranking_data = getCacheFile("getGoogleAnalytics");
if($ranking_data){
$count = 1;
echo '<ul>';
foreach($ranking_data as $result):
echo '<li>rank:'.$count.' <a href="http://'.$result->gethostname().$result->getPagepath().'">'.$result->getPagetitle().'</a>('.$result->getPageviews().')</li>';
$count++;
endforeach;
echo '</ul>';
} else {
echo '現在ランキングを表示出来ません';
}
表示の度に取得していると制限がかかってしまうので、
キャッシュするなどの処理が必要になってきます。
サンプルソースでは、簡易なキャッシュファイルを作成するようにしています。
接続できない時
アカウントの「安全性の低いアプリ」設定が無効になっている可能性があります。
自身のアカウント設定から「安全性の低いアプリのアクセス」を有効にしてみてください。
参考サイト
PHP & JavaScript Room さん
http://phpjavascriptroom.com/?t=topic&p=gapi


コメント