2012-08-15 148 views
3

這是我第一次嘗試使用Core Reporting API。我已經成功通過Hello Analytics教程並且沒有問題地提出API請求。我的問題在於查詢使用維度,度量和過濾器的API。以下是我正在使用的代碼..我能夠顯示我在第一天和第一天之間有多少訪問者。然後顯示其中有多少來自有機搜索。我希望有人可以給我一個例子,用更復雜的請求來查詢API ..也許包括Dimensions,Metrics,Filters ..然後在行中顯示。任何幫助深表感謝。下面是我到目前爲止的代碼...Google Analytics核心報告API PHP查詢

//查詢Core Reporting API

function getResults($analytics, $profileId, $first_day, $today) { 
     return $analytics->data_ga->get(
    'ga:' . $profileId, 
    $first_day, 
    $today, 
    'ga:visits, ga:organicSearches'); 
    } 

//將結果輸出

function printResults(&$results) { 
      if (count($results->getRows()) > 0) { 
    $profileName = $results->getProfileInfo()->getProfileName(); 
    $rows = $results->getRows(); 
    $visits = $rows[0][0]; 
    $organic = $rows[0][1]; 
    print "<h1>$profileName</h1>"; 

    echo '<table border="1" cellpadding="5">'; 

    echo '<tr>'; 
    echo '<td>Visits</td>'; 
    echo '<td>Organic</td>'; 
    echo '</tr>'; 

    echo '<tr>'; 
    echo '<td>'. $visits . '</td>'; 
    echo '<td>'. $organic . '</td>'; 
    echo '</td>'; 

    echo '</table>'; 

    } else { 
     print '<p>No results found.</p>'; 
    } 
} 

回答

3

下面是代碼:

$optParams = array(
     'dimensions' => 'ga:date,ga:customVarValue1,ga:visitorType,ga:pagePath', 
     'sort' => '-ga:visits,ga:date', 
     'filters' => 'ga:visitorType==New', 
     'max-results' => '100'); 

$metrics = "ga:visits"; 
$results = $analytics->data_ga->get(
'ga:' . $profileId, 
'2013-03-01', 
'2013-03-10', 
$metrics, 
$optParams); 

用於顯示結果:

function getRows($results) { 
     $table = '<h3>Rows Of Data</h3>'; 

     if (count($results->getRows()) > 0) { 
     $table .= '<table>'; 

     // Print headers. 
     $table .= '<tr>'; 

     foreach ($results->getColumnHeaders() as $header) { 
      $table .= '<th>' . $header->name . '</th>'; 
     } 
     $table .= '</tr>'; 

     // Print table rows. 
     foreach ($results->getRows() as $row) { 
     $table .= '<tr>'; 
     foreach ($row as $cell) { 
      $table .= '<td>' 
       . htmlspecialchars($cell, ENT_NOQUOTES) 
       . '</td>'; 
     } 
     $table .= '</tr>'; 
     } 
     $table .= '</table>'; 

     } else { 
     $table .= '<p>No results found.</p>'; 
     } 

     return $table; 
    } 

如果您試圖使demo正常工作,您可以更好地理解。
同時參照code

+0

謝謝! $ optParams非常有幫助。 – 472084 2013-09-04 22:37:56

2

這是在api源碼中定義的data_ga->get函數。

public function get($ids, $startDate, $endDate, $metrics, $optParams = array()) 
    { 
    $params = array('ids' => $ids, 'start-date' => $startDate, 'end-date' => $endDate, 'metrics' => $metrics); 
    $params = array_merge($params, $optParams); 
    return $this->call('get', array($params), "Google_Service_Analytics_GaData"); 
    } 

完整的參數列表here

除了身份證,開始日期,結束日期的所有參數和指標是可選的,需要發送的關聯數組get函數的第5 argumant。

相關問題