Analytics API sample 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
 
    require_once 'vendor/autoload.php';
 
    $client_id = '';
 
    $view_id = '';
 
    $private_key = @file_get_contents('');
 
    $from = date('Y-m-d', strtotime('-1 month'));
    $to = date('Y-m-d');
 
    $dimensions = 'ga:date';
    $metrics = 'ga:visits';
 
    $option = array(
        'dimensions' => $dimensions,
        'max-results' => 10,
        'sort' => '-ga:visits',
        'start-index' => 11,
    );
 
    if(isset($_SESSION['service_token']))
    {
        $client->setAccessToken($_SESSION['service_token']);
    }
 
 
    $credentials = new Google_Auth_AssertionCredentials($client_id, $scopes, $private_key);
 
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
 
    if($client->getAuth()->isAccessTokenExpired())
    {
        $client->getAuth()->refreshTokenWithAssertion($credentials);
    }
 
    $_SESSION['service_token'] = $client->getAccessToken();
 
    $analytics = new Google_Service_Analytics($client);
 
    $data = $analytics->data_ga->get('ga:'. $view_id, $from, $to, $metrics, $option);
 
 
 
    $list = array();
    foreach($data['rows'] as $row => $value){
        $result = array();
        foreach($data['columnHeaders'] as $key => $header){
            $result[$header['name']] = $value[$key];
        }
        $list[] = $result;
    }
?>
 
<table>
        <thead>
                <tr>
                        <th>pagepath</th>
                        <th>visits</th>
                </tr>
        </thead>
        <tbody>
        <?php
                foreach($list as $val){
                    echo "<tr>";
                    foreach ($val as $data){
                        echo "<td>$data</td>";
                    }
                    echo "</tr>";
                }
        ?>
</tbody>
</table>