问题
I'm trying to fetch some data using the analytics API, the example i have is this:
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');
}
and the function in the Analytics.php file is:
public function get($ids, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Analytics_RealtimeData");
}
}
How do I adapt that example to return some dimensions along with the sessions, for example, pagePath?
Thanks
回答1:
So the question is little unclear, but the first part of your question is correct, that example works and is the way to get data from the Google Analytics API. You do NOT need to touch or modify Analytics.php however.
Here is what your code should look like:
$ga_profile_id = xxxxxxx; // insert yours
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:visitors,ga:pageviews';
$dimensions = 'ga:date';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
These are all the basic elements you need to get started. Visit https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries for a list of Common Query recipes. Replace the metrics, dimensions and sort parameters in my example above with the ones listed there to run the common report scenarios they cover.
The Analytics API Query explorer (https://ga-dev-tools.appspot.com/query-explorer/) is a great to play around and discover the metric and dimension names. For example, you'll find that that the dimension for Page Path is: ga:pagePath.
So then, for example, if you want to get visits and pageviews by page path, you simply insert the correct parameters in the code, and you get something that looks like this:
$ga_profile_id = xxxxxx; //insert yours here
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:pageviews';
$dimensions = 'ga:pagePath';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
Which basically means: Get the metrics visits and pageviews, using page path as the dimension, and sort it by visits - for the last 2 days! Hopefully this all makes sense.
回答2:
I'm a bit unfamiliar with php syntax but you can specify dimension types in your params when query-ing for example for pagepath you could try
$params = array('ids' => $ids, 'metrics' => $metrics, 'dimensions' => 'rt:pagePath')
See the official dimensions and metrics explorer for more info
来源:https://stackoverflow.com/questions/30535837/get-function-in-google-analytics-api