Search code examples
phpgoogle-apigoogle-analytics-apigoogle-api-php-clientgoogle-reporting-api

PHP: how to retrieve all the metrics and dimensions from the Google Metadata API?


The Metadata API states that it can be used to return the available Google metrics and dimensions. There is a working javascript example page to demonstrate this.

Now I'm looking for a snippet OR documentation page how to achieve this in PHP. I've searched for both without success.

So my question: how do I use the Google PHP lib to retrieve all available metrics and dimensions?


Solution

  • Directly from the documentation on the metadata API you can do this using an API key there is no need for using oauth2

     /**
     * 1. Execute a Metadata Request
     * An application can request columns data by calling the list method on the Analytics service object.
     * The method requires an reportType parameter that specifies the column data to retrieve.
     * For example, the following code requests columns for the ga report type.
     */
    
    try {
    
      $results = $analytics->metadata_columns->listMetadataColumns('ga');
      // Success
    
    } catch (apiServiceException $e) {
      // Handle API service exceptions.
      $error = $e->getMessage();
    }
    
    
    /**
     * 2. Print out the Columns data
     * The components of the result can be printed out as follows:
     */
    
    function printMetadataReport($results) {
      print '<h1>Metadata Report</h1>';
      printReportInfo($results);
      printAttributes($results);
      printColumns($results);
    }
    
    
    function printReportInfo(&$results) {
      $html = '<h2>Report Info</h2>';
      $html .= <<<HTML
    <pre>
    Kind                  = {$results->getKind()}
    Etag                  = {$results->getEtag()}
    Total Results         = {$results->getTotalResults()}
    </pre>
    HTML;
      print $html;
    }
    
    
    function printAttributes(&$results) {
      $html = '<h2>Attribute Names</h2><ul>';
      $attributes = $results->getAttributeNames();
      foreach ($attributes as $attribute) {
        $html .= '<li>'. $attribute . '</li>';
      }
      $html .= '</ul>';
      print $html;
    }
    
    
    function printColumns(&$results) {
      $columns = $results->getItems();
      if (count($columns) > 0) {
        $html = '<h2>Columns</h2>';
        foreach ($columns as $column) {
          $html .= '<h3>' . $column->getId() . '</h3>';
          $column_attributes = $column->getAttributes();
          foreach ($column_attributes as $name=>$value) {
            $html .= <<<HTML
    <pre>
    {$name}: {$value}
    </pre>
    HTML;
          }
        }
      } else {
        $html = '<p>No Results Found.</p>';
      }
      print $html;
    }