[精讚] [會員登入]
2139

設定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

你可能感興趣的文章

[PHP8] 使用autoload autoload+ namespace +use 到了php7之後,namespace和use越來越重要,此篇整理autoload和namespace、use的結合使用。

[PHP] 移除檔案的UTF8 BOM 移除檔案的UTF8 BOM

[CodeIgniter 3] 自寫找不到頁面(page404)的方法 使用CI3框架中如果找不到頁面,就會導到一個自定的404頁面,該怎麼做?

[CodeIgniter 3] 修改或插入資料時遇到函數的處理 CI3 中要新增或修改的資料中如果有 now()這類的函數,要怎麼處理?

PHP程式經驗 #1 -- 靜態的物件比動態物件快 驗證 1. 使用動態物件函式 > 使用靜態物件函式。 2. 使用有宣告的靜態物件函式 > 使用動態無宣告的靜

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

為什麼要重造輪子? 什麼輪子?造什麼輪子?我為什麼要重造輪子?

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

魔球中小女孩唱的歌 The show 魔球中小女孩唱的歌 The show

[PHP] 檢查IP是否在某個網段內 mtachcidr 要檢查IP是否在某個網段內,要寫幾行?10行?5行? 不用,只要2行。以下是我寫的 code /** * matchCI

海棉寶寶超泡杯演奏的sweet victory 章魚哥和海棉寶寶在超泡杯的演奏歌曲