2
votes

I want to use the Analytics API and a PHP script that I run with a cron job once a day, to check the session duration of visitors at my content. This content sites are like this:

  • domain.com/e/3747634

  • domain.com/e/7843735

    ...

The purpose is, if I notice that the session duration is below 5 seconds, it is fake traffic and I can ban this page.

This is the relevant part of my code, there is the authentication part before, but this works and is not so important.

 //calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P1D'));

//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", $date->format('Y-m-d'),  date("Y-m-d"), "ga:users,ga:sessions", $params );


?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){  
    print "<td>".$header['name']."</td>";   
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {    
    print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";  
}

//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
<?php

?>

This displays:

2015-09-02 - 2015-09-03
ga:userType      ga:users ga:sessions
New Visitor        127108 127108
Returning Visitor  5849   13252
Rows Returned 2

How can I get the average session duration of visitors on each of the content pages? (For "today")

1

1 Answers

0
votes

Have a look at the dimensions and metric explorer but i think what you want to do is make the following change to your code:

//Adding Dimensions
$params = array('dimensions' => 'ga:pagepath'); 
// requesting the data
$data = $service->data_ga->get("ga:xxxxxxxx", $date->format('Y-m-d'),    date("Y-m-d"), "ga:avgSessionDuration", $params );

Also the query explorer is a good resource for experimenting with what various dimensions and metrics you want to request from the API.