facebook twitter hatena line email

その他サービス/GoogleAnalytics/サーバサイド

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

phpでサーバサイドでイベントを発生させてanalyticsで計測する方法

ライブラリ

https://code.google.com/p/php-ga/

ダウンロード

wget https://php-ga.googlecode.com/files/php-ga-1.1.1.zip
unzip php-ga-1.1.1.zip
  • GoogleAnalyticsServer.php
require_once APPLICATION_PATH . '/../library/php-ga-1.1.1/src/autoload.php';
use UnitedPrototype\GoogleAnalytics;
class GoogleAnalyticsServer
{
 private $_tracker;
 private $_session;
 private $_visitor;
 public function __construct()
 {
   $this->_tracker = new GoogleAnalytics\Tracker('UA-596xxxx-xx', 'example.com');
   $visitor = new GoogleAnalytics\Visitor();
   $visitor->setIpAddress($_SERVER['REMOTE_ADDR']);
   $visitor->setUserAgent($_SERVER['HTTP_USER_AGENT']);
   $visitor->setScreenResolution('1024x768');
   $this->_visitor = $visitor;
   $this->_session = new GoogleAnalytics\Session();
 }
 public function setPage($url, $title)
 {
   $page = new GoogleAnalytics\Page($url);
   $page->setTitle($title);
   $this->_tracker->trackPageview($page, $this->_session, $this->_visitor);
 }
 public function setEvent($category = "", $action = "", $label = "", $value = "", $noninteraction = "")
 {
   $event = new GoogleAnalytics\Event();
   $event->setCategory($category);
   $event->setAction($action);
   $event->setLabel($label);
   $event->setValue($value);
   $event->setNoninteraction($noninteraction);
   $this->_tracker->trackEvent($event, $this->_session, $this->_visitor);
 }
}
  • main.php
require_once APPLICATION_PATH . '/models/GoogleAnalyticsServer.php';
$ga = new GoogleAnalyticsServer();
$ga->setEvent("category1", "action1", "label1");