I am using the google-api-php-client, installed through composer, v2.0. I need to extract the data per day/week/month etc. However, I am only getting the totals.
I am probably missing one property, but I can't find anywhere what it should be.
This is the request I am using
$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Login to my app');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$analytics = new Google_Service_AnalyticsReporting($client);
function getReport($analytics, $profileId) {
$VIEW_ID = $profileId;
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");
$dateRange2 = new Google_Service_AnalyticsReporting_DateRange();
$dateRange2->setStartDate("14daysAgo");
$dateRange2->setEndDate("7daysAgo");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("Sessions");
$new_users = new Google_Service_AnalyticsReporting_Metric();
$new_users->setExpression("ga:newUsers");
$new_users->setAlias("New users");
$organic = new Google_Service_AnalyticsReporting_Metric();
$organic->setExpression("ga:organicSearches");
$organic->setAlias("Organic results");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges(array($dateRange,$dateRange2));
$request->setMetrics(array($sessions, $new_users, $organic));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
And this returns only the totals of the dateranges that I specified.
I hope you can help me find the missing property or what I'm doing wrong. Thank you.
You need to pass the ga:date
dimensions to group the results by date. You can find the full list of metrics and dimensions, and play with the data, by using Google Analytics Dimensions and Metrics Explorer. As you mentioned in your comment, you would add this to your code:
$date = new Google_Service_AnalyticsReporting_Dimension();
$date->setName("ga:date");
$request->setDimensions(array($date));