Google Analytics PHP API

Gepost door Vincent Kleijnendorst op 27-04-2009 21:10.

Met deze class kun je de Google analytics API gebruiken in PHP. De data uit de API krijg je terug als PHP arrays.

Op http://www.swis.nl/ga staat een voorbeeld, een download en een korte uitleg.

Bestanden van dit script

index.php

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
Voorbeeld:

<?php
 
  // session_start for caching
  session_start();
  
  require 'analytics.class.php';
  
  try {
      
      // construct the class
      $oAnalytics = new analytics('[username]', '[password]');
      
      // set it up to use caching
      $oAnalytics->useCache();
      
      $oAnalytics->setProfileByName('[Google analytics accountname]');
      // or $oAnalytics->setProfileById('ga:123456');
      
      // set the date range
      $oAnalytics->setMonth(date('n'), date('Y'));
      // or $oAnalytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD');
      
      echo '<pre>';
      // print out visitors for given period
      print_r($oAnalytics->getVisitors());
      
      // print out pageviews for given period
      print_r($oAnalytics->getPageviews());
      
      // use dimensions and metrics for output
      // see: http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html
      print_r($oAnalytics->getData(array(   'dimensions' => 'ga:keyword',
                                            'metrics'    => 'ga:visits',
                                            'sort'       => 'ga:keyword')));
      
  } catch (Exception $e) { 
      echo 'Caught exception: ' . $e->getMessage(); 
  }
?>


<?php

/**
 * Google Analytics PHP API
 * 
 * This class can be used to retrieve data from the Google Analytics API with PHP
 * It fetches data as array for use in applications or scripts
 *  
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Credits: http://www.alexc.me/
 * parsing the profile XML to a PHP array
 *   
 *
 * @link http://www.swis.nl
 * @copyright 2009 SWIS BV
 * @author Vincent Kleijnendorst - SWIS BV (vkleijnendorst [AT] swis [DOT] nl)
 * 
 * @version 0.1
 */

  class analytics{
    
    private $_sUser;
    private $_sPass;
    private $_sAuth;
    private $_sProfileId;
    
    private $_sStartDate;
    private $_sEndDate;
    
    private $_bUseCache;
    private $_iCacheAge;
    
    /**
    * public constructor
    * 
    * @param string $sUser
    * @param string $sPass
    * @return analytics
    */
    public function __construct($sUser, $sPass){
        $this->_sUser = $sUser;
        $this->_sPass = $sPass;
        
        $this->_bUseCache = false;
        
        $this->auth();
    }
    
    
    /**
    * Google Authentification, returns session when set
    */
    private function auth(){
        
        if (isset($_SESSION['auth'])){
            $this->_sAuth = $_SESSION['auth'];
            return;
        }
        
        $aPost = array ( 'accountType'   => 'GOOGLE', 
                         'Email'         => $this->_sUser,
                         'Passwd'        => $this->_sPass,
                         'service'       => 'analytics',
                         'source'        => 'SWIS-Webbeheer-4.0');
                         
        $sResponse = $this->getUrl('https://www.google.com/accounts/ClientLogin', $aPost);
    
        $_SESSION['auth'] = '';
        if (strpos($sResponse, "\n") !== false){
            $aResponse = explode("\n", $sResponse);
            foreach ($aResponse as $sResponse){
                if (substr($sResponse, 0, 4) == 'Auth'){
                    $_SESSION['auth'] = trim(substr($sResponse, 5));
                }
            }
        }
        if ($_SESSION['auth'] == ''){
            unset($_SESSION['auth']);
            throw new Exception('Retrieving Auth hash failed!');
        }
        $this->_sAuth = $_SESSION['auth']; 
    }
    
    /**
    * Use caching (bool)
    * Whether or not to store GA data in a session for a given period
    * 
    * @param bool $bCaching (true/false)
    * @param int $iCacheAge seconds (default: 10 minutes)
    */
    public function useCache($bCaching = true, $iCacheAge = 600){
        $this->_bUseCache = $bCaching;
        $this->_iCacheAge = $iCacheAge;
        if ($bCaching && !isset($_SESSION['cache'])){
            $_SESSION['cache'] = array();     
        }
    }
    
    
    /**
    * Get GA XML with auth key
    * 
    * @param string $sUrl
    * @return string XML
    */
    private function getXml($sUrl){
        
        return $this->getUrl($sUrl, array(), array('Authorization: GoogleLogin auth=' . $this->_sAuth));
    }
    
    
    /**
    * Sets GA Profile ID  (Example: ga:12345)
    */        
    public function setProfileById($sProfileId){
        
            $this->_sProfileId = $sProfileId; 
    }
    
    /**
    * Sets Profile ID by a given accountname
    * 
    */
    public function setProfileByName($sAccountName){
        
        if (isset($_SESSION['profile'])){
            $this->_sProfileId = $_SESSION['profile'];
            return;
        }
        
        $this->_sProfileId = '';
        $sXml = $this->getXml('https://www.google.com/analytics/feeds/accounts/default');
        $aAccounts = $this->parseAccountList($sXml);
            
        foreach($aAccounts as $aAccount){
            if (isset($aAccount['accountName']) && $aAccount['accountName'] == $sAccountName){
                if (isset($aAccount['tableId'])){
                    $this->_sProfileId =  $aAccount['tableId'];
                }
            }    
        }
        if ($this->_sProfileId == ''){
            throw new Exception('No profile ID found!');
        }
        
        $_SESSION['profile'] = $this->_sProfileId;
    }
    
    /**
    * Returns an array with profileID => accountName
    * 
    */
    public function getProfileList(){
        
        $sXml = $this->getXml('https://www.google.com/analytics/feeds/accounts/default');
        $aAccounts = $this->parseAccountList($sXml);
        $aReturn = array();
        foreach($aAccounts as $aAccount){ 
            $aReturn[$aAccount['tableId']] =  $aAccount['title'];
        }       
        return $aReturn;
    }
    
    /**
    * get resulsts from cache if set and not older then cacheAge
    * 
    * @param string $sKey
    * @return mixed cached data
    */
    private function getCache($sKey){
        
        if ($this->_bUseCache === false){
            return false;
        }
        
        if (!isset($_SESSION['cache'][$this->_sProfileId])){
            $_SESSION['cache'][$this->_sProfileId] = array();
        }  
        if (isset($_SESSION['cache'][$this->_sProfileId][$sKey])){
            if (time() - $_SESSION['cache'][$this->_sProfileId][$sKey]['time'] < $this->_iCacheAge){
                return $_SESSION['cache'][$this->_sProfileId][$sKey]['data'];
            } 
        }
        return false;
    }
    
    /**
    * Cache data in session
    * 
    * @param string $sKey
    * @param mixed $mData Te cachen data
    */
    private function setCache($sKey, $mData){
        
        if ($this->_bUseCache === false){
            return false;
        }
        
        if (!isset($_SESSION['cache'][$this->_sProfileId])){
            $_SESSION['cache'][$this->_sProfileId] = array();
        }  
        $_SESSION['cache'][$this->_sProfileId][$sKey] = array(  'time'  => time(),
                                                                'data'  => $mData);
    }
    
    /**
    * Parses GA XML to an array (dimension => metric)
    * Check http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html 
    * for usage of dimensions and metrics
    * 
    * @param array  $aProperties  (GA properties: metrics & dimensions)
    * 
    * @return array result
    */
    public function getData($aProperties = array()){
        $aParams = array();
        foreach($aProperties as $sKey => $sProperty){
            $aParams[] = $sKey . '=' . $sProperty;
        }
        
        $sUrl = 'https://www.google.com/analytics/feeds/data?ids=' . $this->_sProfileId . 
                                                        '&start-date=' . $this->_sStartDate . 
                                                        '&end-date=' . $this->_sEndDate . '&' . 
                                                        implode('&', $aParams);
        $aCache = $this->getCache($sUrl);
        if ($aCache !== false){
            return $aCache;
        }
        
        $sXml = $this->getXml($sUrl);
        
        $aResult = array();
        
        $oDoc = new DOMDocument();
        $oDoc->loadXML($sXml);
        $oEntries = $oDoc->getElementsByTagName('entry');
        foreach($oEntries as $oEntry){
            $oTitle = $oEntry->getElementsByTagName('title');
            $sTitle = $oTitle->item(0)->nodeValue;
            
            $oMetric = $oEntry->getElementsByTagName('metric'); 
            
            // Fix the array key when multiple dimensions are given
            if (strpos($sTitle, ' | ') !== false && strpos($aProperties['dimensions'], ',') !== false){
                
                $aDimensions = explode(',', $aProperties['dimensions']);
                $aDimensions[] = '|';
                $aDimensions[] = '=';
                $sTitle = preg_replace('/\s\s+/', ' ', trim(str_replace($aDimensions, '', $sTitle)));  
                
            }
            $sTitle = str_replace($aProperties['dimensions'] . '=', '', $sTitle);
            
            $aResult[$sTitle] = $oMetric->item(0)->getAttribute('value');
        }
        // cache the results (if caching is true)
        $this->setCache($sUrl, $aResult);
        
        return $aResult;
    }
    
    /**
    * Parse XML from account list
    * 
    * @param string $sXml
    */
    private function parseAccountList($sXml){
        
        $oDoc = new DOMDocument();
        $oDoc->loadXML($sXml);
        $oEntries = $oDoc->getElementsByTagName('entry');
        $i = 0;
        $aProfiles = array();
        foreach($oEntries as $oEntry){
            
            $aProfiles[$i] = array();

            $oTitle = $oEntry->getElementsByTagName('title');
            $aProfiles[$i]["title"] = $oTitle->item(0)->nodeValue;

            $oEntryId = $oEntry->getElementsByTagName('id');
            $aProfiles[$i]["entryid"] = $oEntryId->item(0)->nodeValue;

            $oProperties = $oEntry->getElementsByTagName('property');
            foreach($oProperties as $oProperty){
                if (strcmp($oProperty->getAttribute('name'), 'ga:accountId') == 0){
                    $aProfiles[$i]["accountId"] = $oProperty->getAttribute('value');
                }    
                if (strcmp($oProperty->getAttribute('name'), 'ga:accountName') == 0){
                    $aProfiles[$i]["accountName"] = $oProperty->getAttribute('value');
                }
                if (strcmp($oProperty->getAttribute('name'), 'ga:profileId') == 0){
                    $aProfiles[$i]["profileId"] = $oProperty->getAttribute('value');
                }
                if (strcmp($oProperty->getAttribute('name'), 'ga:webPropertyId') == 0){
                    $aProfiles[$i]["webPropertyId"] = $oProperty->getAttribute('value');
                }
            }

            $oTableId = $oEntry->getElementsByTagName('tableId');
            $aProfiles[$i]["tableId"] = $oTableId->item(0)->nodeValue;

            $i++;
        }
        return $aProfiles;
    }
    
    /**
    * Get data from given URL
    * Uses Curl if installed, falls back to file_get_contents if not
    * 
    * @param string $sUrl
    * @param array $aPost
    * @param array $aHeader
    * @return string Response
    */
    private function getUrl($sUrl, $aPost = array(), $aHeader = array()){
        
        
        if (count($aPost) > 0){
            // build POST query
            $sMethod = 'POST'; 
            $sPost = http_build_query($aPost);    
            $aHeader[] = 'Content-type: application/x-www-form-urlencoded';
            $aHeader[] = 'Content-Length: ' . strlen($sPost);
            $sContent = $aPost;
        } else {
            $sMethod = 'GET';
            $sContent = null;
        }
        
        if (function_exists('curl_init')){

            // If Curl is installed, use it!
            $rRequest = curl_init();
            curl_setopt($rRequest, CURLOPT_URL, $sUrl);
            curl_setopt($rRequest, CURLOPT_RETURNTRANSFER, 1);
            
            if ($sMethod == 'POST'){
                curl_setopt($rRequest, CURLOPT_POST, 1); 
                curl_setopt($rRequest, CURLOPT_POSTFIELDS, $aPost); 
            } else {
                curl_setopt($rRequest, CURLOPT_HTTPHEADER, $aHeader);
            }
            
            $sOutput = curl_exec($rRequest);
            if ($sOutput === false){
                throw new Exception('Curl error (' . curl_error($rRequest) . ')');    
            }
            
            $aInfo = curl_getinfo($rRequest);
            
            if ($aInfo['http_code'] != 200){
                // not a valid response from GA
                if ($aInfo['http_code'] == 400){
                    throw new Exception('Bad request (' . $aInfo['http_code'] . ') url: ' . $sUrl);     
                }
                if ($aInfo['http_code'] == 403){
                    throw new Exception('Access denied (' . $aInfo['http_code'] . ') url: ' . $sUrl);     
                }
                throw new Exception('Not a valid response (' . $aInfo['http_code'] . ') url: ' . $sUrl);
            }
            
            curl_close($rRequest);
                        
        } else {
            // Curl is not installed, use file_get_contents
            
            // create headers and post
            $aContext = array('http' => array ( 'method' => $sMethod,
                                                'header'=> implode("\r\n", $aHeader) . "\r\n",
                                                'content' => $sContent));
            $rContext = stream_context_create($aContext);

            $sOutput = @file_get_contents($sUrl, 0, $rContext);
            if (strpos($http_response_header[0], '200') === false){
                // not a valid response from GA   
                throw new Exception('Not a valid response (' . $http_response_header[0] . ') url: ' . $sUrl);       
            }
        }
        return $sOutput;
    }   
    
    /**
    * Sets the date range for GA data
    * 
    * @param string $sStartDate (YYY-MM-DD)
    * @param string $sEndDate   (YYY-MM-DD)
    */
    public function setDateRange($sStartDate, $sEndDate){
        
        $this->_sStartDate = $sStartDate; 
        $this->_sEndDate   = $sEndDate;
        
    }
    
    /**
    * Sets de data range to a given month
    * 
    * @param int $iMonth
    * @param int $iYear
    */
    public function setMonth($iMonth, $iYear){  
        
        $this->_sStartDate = date('Y-m-d', strtotime($iYear . '-' . $iMonth . '-01')); 
        $this->_sEndDate   = date('Y-m-d', strtotime($iYear . '-' . $iMonth . '-' . date('t', strtotime($iYear . '-' . $iMonth . '-01'))));
    }
    
    /**
    * Get visitors for given period
    * 
    */
    public function getVisitors(){
                                
        return $this->getData(array( 'dimensions' => 'ga:day',
                                     'metrics'    => 'ga:visits',
                                     'sort'       => 'ga:day'));
    }
    
    /**
    * Get pageviews for given period
    * 
    */    
    public function getPageviews(){
                                
        return $this->getData(array( 'dimensions' => 'ga:day',
                                     'metrics'    => 'ga:pageviews',
                                     'sort'       => 'ga:day'));
    }
    
    /**
    * Get visitors per hour for given period
    * 
    */    
    public function getVisitsPerHour(){
        
        return $this->getData(array( 'dimensions' => 'ga:hour',
                                     'metrics'    => 'ga:visits',
                                     'sort'       => 'ga:hour'));
    }
    
    /**
    * Get Browsers for given period
    * 
    */    
    public function getBrowsers(){
        
        $aData = $this->getData(array(  'dimensions' => 'ga:browser,ga:browserVersion',
                                        'metrics'    => 'ga:visits',
                                        'sort'       => 'ga:visits'));             
        arsort($aData);
        return $aData;                                                                                                                                                                           
    }
    
    /**
    * Get Operating System for given period
    * 
    */    
    public function getOperatingSystem(){
        
        $aData = $this->getData(array(   'dimensions' => 'ga:operatingSystem',
                                         'metrics'    => 'ga:visits',
                                         'sort'       => 'ga:visits'));
        // sort descending by number of visits
        arsort($aData);
        return $aData; 
    }

    /**
    * Get screen resolution for given period
    * 
    */    
    public function getScreenResolution(){
        
        $aData = $this->getData(array(   'dimensions' => 'ga:screenResolution',
                                         'metrics'    => 'ga:visits',
                                         'sort'       => 'ga:visits'));
        
        // sort descending by number of visits 
        arsort($aData);
        return $aData; 
    }
    
    /**
    * Get referrers for given period
    * 
    */    
    public function getReferrers(){
        
        $aData = $this->getData(array(   'dimensions' => 'ga:source',
                                         'metrics'    => 'ga:visits',
                                         'sort'       => 'ga:source'));
    
        // sort descending by number of visits 
        arsort($aData);
        return $aData; 
    }
    
    /**
    * Get search words for given period
    * 
    */    
    public function getSearchWords(){
        $aData = $this->getData(array(   'dimensions' => 'ga:keyword',
                                         'metrics'    => 'ga:visits',
                                         'sort'       => 'ga:keyword'));
        // sort descending by number of visits                                                                                                                                                     
        arsort($aData);
        return $aData; 
    }
}
?>

Commentaar

Inloggen wachtwoord vergeten? Aanmelden