title: PHP Google Analytics Reporting API. Retrieve data in chart
body: <p>I am using the Google Analytics Reporting API v4 in PHP.</p>
  
  <p>I want to show the following data on a dashboard from another web page: list of the referrer urls and sessions coming from them at 30 and 120 days.</p>
  
  <p>For that, I copied the code provided in the API documentation for web server applications (<a href="https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php" rel="nofollow noreferrer">https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php</a>) and made the pertinent changes to get the mentioned data. </p>
  
  <p>My problem comes when I try to retrieve the data independently to use it to feed a chart. </p>
  
  <p>Here is the Google Analytics Reporting API code, with modifications:</p>
  
  <pre><code>    // Load the Google API PHP Client Library.
  require_once __DIR__ . '/vendor/autoload.php';
  
  session_start();
  
  $client = new Google_Client();
  $client-&gt;setAuthConfig(__DIR__ . '/client_secrets.json');
  $client-&gt;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']) &amp;&amp; $_SESSION['access_token']) {
    // Set the access token on the client.
    $client-&gt;setAccessToken($_SESSION['access_token']);
  
    // Create an authorized analytics service object.
    $analytics = new Google_Service_AnalyticsReporting($client);
  
    // Call the Analytics Reporting API V4.
    $response = getReport($analytics); //see function below
  
  
  } else {
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  }
  
  
  /**
   * 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 = "888888888"; //View ID replaced 
  
    // Create the DateRange objects.
    $monthly = new Google_Service_AnalyticsReporting_DateRange();
    $monthly-&gt;setStartDate("30daysAgo");
    $monthly-&gt;setEndDate("today");
  
    $quarterly = new Google_Service_AnalyticsReporting_DateRange();
    $quarterly-&gt;setStartDate("120daysAgo");
    $quarterly-&gt;setEndDate("today");
  
    // Create the Metrics objects.
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions-&gt;setExpression("ga:sessions");
    $sessions-&gt;setAlias("sessions");
  
    // Create the Dimensions object.
    $fullReferrer = new Google_Service_AnalyticsReporting_Dimension();
    $fullReferrer-&gt;setName("ga:fullReferrer");
  
    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request-&gt;setViewId($VIEW_ID);
    $request-&gt;setDateRanges(array($monthly, $quarterly));
    $request-&gt;setMetrics(array($sessions));
    $request-&gt;setDimensions(array($fullReferrer));
  
    //Call the batchGet method.
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body-&gt;setReportRequests( array( $request) );
    return $analytics-&gt;reports-&gt;batchGet( $body );
  
  /**
   * Parses and prints the Analytics Reporting API V4 response.
   *
   * @param An Analytics Reporting API V4 response.
   */
  
  function printResults($reports) {
    for ( $reportIndex = 0; $reportIndex &lt; count( $reports ); $reportIndex++ ) {
      $report = $reports[ $reportIndex ];
      $header = $report-&gt;getColumnHeader();
      $dimensionHeaders = $header-&gt;getDimensions();
      $metricHeaders = $header-&gt;getMetricHeader()-&gt;getMetricHeaderEntries();
      $rows = $report-&gt;getData()-&gt;getRows();
      for ( $rowIndex = 0; $rowIndex &lt; count($rows); $rowIndex++) {
        $row = $rows[ $rowIndex ];
        $dimensions = $row-&gt;getDimensions();
        $metrics = $row-&gt;getMetrics();
        for ($i = 0; $i &lt; count($dimensionHeaders) &amp;&amp; $i &lt; count($dimensions); $i++) {
             $items_dim = array();
         foreach ($dimensions as $k =&gt;$data){
              $items_dim[] = $data;
              }
              print_r($items_dim);  
        }
  
        for ($j = 0; $j &lt; count($metrics); $j++) {
          $values = $metrics[$j]-&gt;getValues();
         for ($k = 0; $k &lt; count($values); $k++) {
            $entry = $metricHeaders[$k];
  
              $items_val = array();           
              foreach ($values as $k =&gt;$data){
              $items_val[] = $data;
            }
             print_r($items_val);
          }
        }
       }
    }
  }
  
  printResults($response-&gt;getReports());
     ?&gt;
  </code></pre>
  
  <p>With the modifications I made, I managed to get a result  out of the </p>
  
  <pre><code>    printResults($response-&gt;getReports());
  </code></pre>
  
  <p>that looks like an array:</p>
  
  <p><em>Array ( [0] => <strong>(direct)</strong> ) Array ( [0] => 20 ) Array ( [0] => 168 ) Array ( [0] => <strong>url1</strong> ) Array ( [0] => 0 ) Array ( [0] => 3 ) Array ( [0] => <strong>url2</strong> ) Array ( [0] => 0 ) Array ( [0] => 3 ) Array ( [0] => <strong>url3</strong> ) Array ( [0] => 0 ) Array ( [0] => 11 ) Array ( [0] => <strong>url4</strong> ) Array ( [0] => 0 ) Array ( [0] => 3 ) ...</em></p>
  
  <p>The [0] references the sessions object. There are three items: </p>
  
  <ul>
  <li>url.</li>
  <li>sessions at 30 days.</li>
  <li>sessions at 120 days.</li>
  </ul>
  
  <p>So the question is <strong>how to retrieve the data from the result of the function so that it can be used independently to feed a chart</strong>. </p>
  
  <p>So far, I tried to store the function in a variable $results, so that then I can iterate through the array, but it is not working:</p>
  
  <pre><code>$results = printResults($response-&gt;getReports());
  print ($results);
  </code></pre>
  
  <p>The above code prints one time the results.</p>
  
  <pre><code>$results = printResults($response-&gt;getReports());
  //print ($results);
  </code></pre>
  
  <p>The above code prints one time the results too, so the work is done by the pintResults() function, not by the print(). </p>
  
  <p>I also tried to get stored in a variable $results when the function is defined (not working neither):</p>
  
  <pre><code>$results = function printResults($reports) {
    for ( $reportIndex = 0; $reportIndex &lt; count( $reports ); $reportIndex++ ) {
      $report = $reports[ $reportIndex ];
      $header = $report-&gt;getColumnHeader();
      ...
  </code></pre>