Search code examples
phpgoogle-apigoogle-analytics-apigoogle-api-php-client

How to use parameters in Google Analytics API


How to use parameters in getResults function? I need to get information about what urls of my website users are watching. In case when i use ga:sessions, I see how many users was there. If I change it to ga:pageviews the number (in result array) is changes. So it means that API is "alive".

How do I get URLs "points of enter" where people starting to watch my website. And how to send parameters in this place 'ga:sessions'); ? API instructions I was reading are here.

function getResults(&$analytics, $profileId) {
  // Calls the Core Reporting API and queries for the number of sessions
  // for the last seven days.
   return $analytics->data_ga->get(
       'ga:' . $profileId,

       '7daysAgo',
       'today',
       'ga:sessions');
}

function printResults(&$results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();
//    $sessions = $rows[0][0];

    // Print the results.

    echo '<pre>';
    print_r($rows);


  } else {
    print "No results found.\n";
  }
}

For now result is:

Array
(
    [0] => Array
        (
            [0] => 3585
        )

)

Solution

  • When you run your request

    $analytics->data_ga->get('ga:' . $profileId,    
                             '7daysAgo',
                             'today',
                             'ga:sessions');
    

    What you are doing is asking Google Analytics to give you the number of sessions for your profile between today and 7 days ago. Which it is infact doing. There have been 3585 sessions during that time frame

    Now if you check the dimensions and metrics explorer you will find a large list of dimensions and metrics. ga:sessions is a metric ga:pageviews is a dimension so you need to add the dimension to your request.

    $params = array('dimensions' => 'ga:pageviews');    
    $analytics->data_ga->get('ga:' . $profileId,    
                             '7daysAgo',
                             'today',
                             'ga:sessions',
                             $params);
    

    Now run your request and you should get a list of each page with the total number of sessions for that page.

    Tip:

    foreach ($results->getRows() as $row) {         
        print $row[0]." - ".$row[1];
    }