Search code examples
phpgoogle-analyticsgoogle-analytics-api

Google Analytics API v3 how to extract values?


I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.

e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...

But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.

Anyone who can help would be greatly appreciated.

$ids   = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';    
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
  get($ids, $start_date, $end_date, $metrics, $optParams);

foreach($data['totalsForAllResults'] as $rows) :

    echo $rows['ga:pagePath']; // why returning a single digit value?
    echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;

Solution

  • $data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:

    foreach ($data->getRows() as $row) :
    

    And then you can iterate $rows for every cell.

    Check this full example:

    private printDataTable(&$results) {
      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>';
      }
      print $table;
    }
    

    source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working