How to create analytics api to show live user in php

1) Open the Service accounts page. 
2) Select a project or create a project

3) Create service account

4)  Select furnish a new private key. 

5) Click create.

6) Now create a folder named "jquerytraining-analytics"  in d:\ drive

7) Open command line and type the following command (if no command line you can use CMDR to install CMDR click here)

   composer require google/apiclient:^2.0
   
 8) Now move the previously donloded file to the same folder and rename it as "service-account-credentials.json"

 9) Now Replace the value of VIEW_ID. 
  
 10)To find a View ID go the the Account Explorer.
 
 11) The view id will be the Table id under the selected account and it looks like "ga:xxxxxxxxx"
 
 12) Now create a index.php file in the folder and write the following code
 
 
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);


/**
 * Initializes an Analytics Reporting API V4 service object.
 *
 * @return An authorized Analytics Reporting API V4 service object.
 */
function initializeAnalytics()
{

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  $analytics = new Google_Service_AnalyticsReporting($client);
  $service = new Google_Service_Analytics($client);
   $VIEW_ID = "ga:xxxxxxxxx";
  $result = $service->data_realtime->get(
        $VIEW_ID,
        'rt:activeVisitors'
    );
   print 'Total visitor now: '.$result->totalsForAllResults['rt:activeVisitors'].'
'; return $analytics; } /** * Queries the Analytics Reporting API V4. * * @param service An authorized Analytics Reporting API V4 service object. * @return The Analytics Reporting API V4 response. */ function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "ga:xxxxxxxxx"; // Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("28daysAgo"); $dateRange->setEndDate("today"); // Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); } /** * Parses and prints the Analytics Reporting API V4 response. * * @param An Analytics Reporting API V4 response. */ function printResults($reports) { //print_r($reports); for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) { $report = $reports[ $reportIndex ]; $header = $report->getColumnHeader(); $dimensionHeaders = $header->getDimensions(); $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); $rows = $report->getData()->getRows(); for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { $row = $rows[ $rowIndex ]; $dimensions = $row->getDimensions(); $metrics = $row->getMetrics(); for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); } for ($j = 0; $j < count($metrics); $j++) { $values = $metrics[$j]->getValues(); for ($k = 0; $k < count($values); $k++) { $entry = $metricHeaders[$k]; print($entry->getName() . ": " . $values[$k] . "\n"); } } } } }

1 thought on “How to create analytics api to show live user in php

Leave comment

Your email address will not be published. Required fields are marked with *.