[精讚] [會員登入]
2313

設定Google analytics API #2 -- PHP的程式安裝和撰寫

讓你的網站能夠存取你的Google analytics上面的資料

分享此文連結 //n.sfs.tw/11587

分享連結 設定Google analytics API #2 -- PHP的程式安裝和撰寫@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 10:24:22 最後編修
2017-08-10 02:43:49 By 張○○
 

自動目錄

此文分成三個部分

設定Google analytics API #1 -- Google網站上的設定

設定Google analytics API #2 -- PHP的程式安裝和撰寫

設定Google analytics API #3 -- 查詢範例

三、安裝Google的Library(PHP)

google的文件[1]說明要用composer安裝他的library,如果你沒有composer,可以參考 [Centos7] 安裝php套件管理程式Composer+ Codeignioter3 這裡來安裝,基本上安裝google library沒有任何問題。

$ composer require google/apiclient:^2.0

安裝完畢後你會出現一個google的library目錄

google/
├── apiclient
├── apiclient-services
└── auth

四、叫用 google apiclient

只要依composer 的方式載入即可,因為我把google的範例放到CI3的類別中,所以寫法稍有改變,基本上大部分依[1]所寫的範例作測試。

叫用

public function doAnalytics(){
    include  APPPATH. "third_party/autoload.php";  //載入composer的 autoload
    $analytics = $this->initializeAnalytics();  //載入帳號資料
    $profileid = $this->getProfileIdByName($analytics,'新精讚');
    $results = $this->getResults($analytics, $profileid); //由profile id取回資料
    $this->printResults($results);
}

初始化載入帳號資料

private function initializeAnalytics()
{
    $KEY_FILE_LOCATION = APPPATH. "config/note_ana.json";
    $client = new Google_Client();
    $client->setApplicationName("Hello Analytics Reporting");
    $client->setAuthConfig($KEY_FILE_LOCATION);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_Analytics($client);
    return $analytics;
}

第3行 note_ana.json 就是前面二步驟下載的json檔,請確認路徑正確

由property name取回profile id

其中的name就是property name,也就是你在google analytics上面設定的名稱,例如:

private function getProfileIdByName($analytics,$name) {
    $accounts = $analytics->management_accounts->listManagementAccounts();
    if (count($accounts->getItems()) <= 0) {
      throw new Exception('No accounts found for this user.');
    }
    $accitems = $accounts->getItems();
    $firstAccountId = $accitems[0]->getId();
    $properties = $analytics->management_webproperties 
->listManagementWebproperties($firstAccountId);
    $items = $properties->getItems();
    if (count($items) <= 0) throw new Exception('No properties found for this user.');
    $n=-1;
    foreach($items as $k=>$one){
      if(!strcmp($one->getName(),$name)){$n=$k; break;}
    }
    if($n==-1)throw new Exception('No profile found for this name.');
    $PropertyId = $items[$n]->getId();
    $profiles = $analytics->management_profiles 
->listManagementProfiles($firstAccountId, $PropertyId);
    if (count($profiles->getItems()) <= 0) {
      throw new Exception('No views (profiles) found for this user.');
    }
    $profileobj= $profiles->getItems();
    return $profileobj[0]->getId();
}

1-7行 取回account id,有多筆取回第1筆
8-10行 取回properties的項目,一個帳號可能有多個google analytics的properties
12-17行 判斷取回的properties名稱是否符合,優先符合優先取回 property id
18-24行 每個property可能有單個或多個profile,取回第一個profile的id

取回資料項目

private function getResults($analytics, $profileId) {
    // Calls the Core Reporting API and queries for the number of sessions
    // for the last seven days.
    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
}

其中的參數可參考[3][4]:
  第5行:VIEW_ID: ga:132128590
  第6行:起始日期
  第7行:結束日期
  第8行:matrics,查詢session

印出結果

此部分和Google文件提供的一樣,請自行發揮了

private function printResults($results) {
    if (count($results->getRows()) > 0) {
      $profileName = $results->getProfileInfo()->getProfileName();
      $rows = $results->getRows();
      $sessions = $rows[0][0];
      print "First view (profile) found: $profileName\n";
      print "Total sessions: $sessions\n";
    } else {
      print "No results found.\n";
    }
}

執行結果

First view (profile) found: 所有網站資料
Total sessions: 5678

下一篇 設定Google analytics API #3 -- 查詢範例

參考資料

[1] https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-php

[2] 所有API的文件請參考 https://developers.google.com/analytics/devguides/config/mgmt/v3/

[3] https://developers.google.com/analytics/devguides/reporting/core/v3/reference

[4] https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide

[5] Hierarchy of accounts, users, properties, and views https://support.google.com/analytics/answer/1009618

END

你可能感興趣的文章

[PHP] 好用的php常數 介紹PHP中 __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__等常數

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔

[CodeIgniter 3] COOKIE的使用 PHP CodeIgniter 3 中COOKIE的使用超簡單

設定Google analytics API #2 -- PHP的程式安裝和撰寫 讓你的網站能夠存取你的Google analytics上面的資料

[PHP7] 利用Memcached 儲存 Session Memcached+ PHP7,利用Memcached 儲存 Session。

[PHP] 處理mail 函式的標題中文字亂碼 PHP的mail函式若標題有中文字得先處理過,否則收信者會看到亂碼

隨機好文

UTF-8的網頁但IE8一片空白 UTF8編碼的網頁在Firefox 正常顯示、但IE8 就是空白,IE8編碼設定是「自動偵測」可是自動偵測到的是 big5...

詭異的創業思維 創業的思維中,有多少銀彈,有多少技術,有多少人脈,有多少時間等等,每個都要考慮進去,以熱忱建立的關係脆弱的像蘇打餅乾一樣..

設計的工作絕不接受比價 拿買陽春麵的價格想買牛肉麵,寧願倒掉也不賣

問問題 問問題其實內涵很深,我悟了很久才懂。 有人問題的目的並不一定是想要得到答案,有時只是純粹想問問題..

維修海棉拖把頭 這類型的海棉拖把很好用,可是這近發現海棉頭越來越不耐用,也許是錯覺,以往都能用個三四個月,現在二個月就差不多掉下來。 這