2012-08-15 189 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。

相关问题