Thursday, July 28, 2016

GET ANALYTICS REPORTS FROM GOOGLE ANALYTICS

Get analytics Reports from Google Analytics

Refer to the url: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php

Follow the url and use this script:
I have copied the library without using the composer and it worked fine!

<?php

// Load the Google API PHP Client Library.
require_once 'vendor/autoload.php';
session_start();
//print_r($_SERVER);
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
  $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_AnalyticsReporting($client);
//echo '<pre>'; print_r($analytics);echo "Hello"; die;
  // Call the Analytics Reporting API V4.
  $response = getReport($analytics);
  
//echo '<pre>'; print_r($response); die('sss'); 
 printResults($response);

} else {
    $redirect_uri = 'http://localhost/scripts/AnalyticsReports/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function getReport(&$analytics) {

  // Replace with your view ID. E.g., XXXX. WE CAN GET THE VIEW ID BY GOING TO analytics.google.com account and then go to admin.
  $VIEW_ID = "11111111";
  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("365daysAgo");
  $dateRange->setEndDate("today");

  // Create the Metrics object.

$metric4 = new Google_Service_AnalyticsReporting_Metric();
$metric4->setExpression("ga:sessions");
$metric4->setAlias("sessions");

$metric5 = new Google_Service_AnalyticsReporting_Metric();
$metric5->setExpression("ga:transactions");
$metric5->setAlias("Transactions");

$metric6 = new Google_Service_AnalyticsReporting_Metric();
$metric6->setExpression("ga:transactionsPerSession");
$metric6->setAlias("EcommerceConversionRate");

$metric7 = new Google_Service_AnalyticsReporting_Metric();
$metric7->setExpression("ga:transactionRevenue");
$metric7->setAlias("Revenue");


$metric8 = new Google_Service_AnalyticsReporting_Metric();
$metric8->setExpression("ga:newUsers");
$metric8->setAlias("newUsers");

$metric9 = new Google_Service_AnalyticsReporting_Metric();
$metric9->setExpression("ga:percentNewSessions");
$metric9->setAlias("percentNewSessions");

$metric10 = new Google_Service_AnalyticsReporting_Metric();
$metric10->setExpression("ga:avgSessionDuration");
$metric10->setAlias("avgSessionDuration");

$metric11 = new Google_Service_AnalyticsReporting_Metric();
$metric11->setExpression("ga:pageviewsPerSession");
$metric11->setAlias("pageviewsPerSession");

$metric12 = new Google_Service_AnalyticsReporting_Metric();
$metric12->setExpression("ga:bounceRate");
$metric12->setAlias("bounceRate");

$dimension = new Google_Service_AnalyticsReporting_Dimension();
$dimension->setName("ga:campaign");
  // Create the ReportRequest object.

  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  
  $request->setViewId($VIEW_ID);
  
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($metric4,$metric5,$metric6,$metric7,$metric8,$metric9,$metric10,$metric11,$metric12));
  $request->setDimensions(array($dimension));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );

  return $analytics->reports->batchGet( $body );
}

function printResults(&$reports) {
$datas = array();
$dim = array();
$val = array();
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();
//echo '<pre>'; print_r($rows); die();
    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
 //$datas[$rowIndex]['dimensions'] = $dimensions;
 $dim[] = $dimensions[0];
      $metrics = $row->getMetrics();
      for($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        //print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];
        $values = $metrics[$j];
$val[] = $values['values'];
//echo '<pre>'; print_r($metrics);
        //print("Metric type: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
 
          //print($entry->getName() . ": " . $value . "\n");
        }
      }
    }
  }
  $msg[0]= "Result status for time ".date('Y-m-d');
  $res = makeArray($dim,$val);
  //echo '<pre>'; print_r($dim); print_r($val);
  if(($res!='FALSE')&&($res >0)){
$msg[] = "Successfully written data into file";
  }else{
$msg[] = "Couldnt write into file";
  }
  echo "Hello";
echo '<pre>'; print_r($msg);
}

 function makeArray($dim,$val){  
        //WRITING THE ARRAY INTO CSV FILE
//print_r($_SERVER);


//echo '<pre>'; print_r($dim); print_r($val); die('TTATT');
//$fileName = 'analyticsReports.csv';
$fileName = $_SERVER['HTTP_HOST'].'/fouzia/scripts/reports/Reports.csv';
$fileName = '/mnt/nfs/fouzia/scripts/reports/Reports.csv';//It can't be an http address as we want to write into it 
$output = fopen($fileName,'w') or die("Can't open php://output");
fputcsv($output, array('CampaignName','sessions','newSessionsPercentage',
'newUsers','bounceRate','pagesPerSession','avgSessionDuration',
'ecommerceConversionRate','transactions','revenue'));
for($i=0;$i<count($dim);$i++){
$campaignName = $dim[$i];
$sessions = $val[$i][0];
$transactions = $val[$i][1];
$ecommerceConversionRate = round($val[$i][2],2);
$ecommerceConversionRate = $ecommerceConversionRate.'%';
$revenue = $val[$i][3];
$newUsers = $val[$i][4];
$newSessionsPercentage = round($val[$i][5],2);
$newSessionsPercentage = $newSessionsPercentage.'%';
$avgSessionDuration = $val[$i][6];
$pagesPerSession = round($val[$i][7],2);
$bounceRate = round($val[$i][8],2);
$bounceRate = $bounceRate.'%';
$write = fputcsv($output, array($campaignName,$sessions,$newSessionsPercentage,
$newUsers,$bounceRate,$pagesPerSession,$avgSessionDuration,
$ecommerceConversionRate,$transactions,$revenue));
}
return $write;

 }

No comments:

Post a Comment