$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 ) ; // Googleクライアントのインスタンスを作成 $client = new Google_Client() ; $client->setAssertionCredentials( $credentials ) ; // トークンのリフレッシュ if( $client->getAuth()->isAccessTokenExpired() ) { $client->getAuth()->refreshTokenWithAssertion( $credentials ) ; } // セッションの設定 $_SESSION['service_token'] = $client->getAccessToken() ; // Analyticsのインスタンスを作成 $analytics = new Google_Service_Analytics( $client ) ; // データの取得 $obj = $analytics->data_ga->get( 'ga:' . $view_id , $from , $to , $metrics , $option ) ; // JSONデータに変換 $json = json_encode( $obj ) ; // HTML用 $html = '' ; // 実行結果を出力 $html .= '

実行結果

' ; $html .= '

' . date( 'Y/m/d' , strtotime( $from ) ) . 'の、ページビューのデイリーランキングを取得してみました。値はサンプル用のダミーです。

' ; // エラー判定 if( !isset($obj->rows) ) { $html .= '

データを取得できませんでした…。

' ; } else { $html .= '
    ' ; // 解析 for( $i=0 , $l=count( $obj->rows ) ; $l > $i ; $i++ ) { // エイリアス $item = $obj->rows[ $i ] ; // 出力 $html .= '
  1. ' . $item[0] . ' (' . number_format( $item[3] ) . 'PV)
  2. ' ; } $html .= '
' ; } // 取得したデータ $html .= '

取得したデータ(JSON)

' ; $html .= '' ; ?> Google Analytics APIでデータを取得するサンプルデモ

配布元: Syncer