Pour intégrer Google Analytics à mon système de blog je me suis constitué une petite classe PHP5. Cette classe est implémentée selon le design pattern Singleton. Le constructeur dispose des identifiants de connexion en dur mais on peut très bien utiliser des constantes.
{
private $email;
private $passwd;
private $ids;
private $auth;
private static $instance;
private function __construct()
{
$this->login('********@********', '********', '********');
}
private function __clone()
{}
public static function instance()
{
if(!isset(self::$instance))
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
private function login($email, $passwd, $ids)
{
$this->email = $email;
$this->passwd = $passwd;
$this->ids = $ids;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => $this->email,
'Passwd' => $this->passwd,
'source'=>'CLI_GAnalytics',
'service'=>'analytics');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$hasil = curl_exec($ch);
$hasil = @split("Auth=", $hasil);
curl_close($ch);
$this->auth = $hasil[1];
}
public function getDimensionByMetric($metrics, $dimensions, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metrics . "&dimensions=ga:" . $dimensions . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
$data = '';
$label = '';
foreach($XML_object->entry as $m)
{
$tmp = @split('ga:' . $dimensions . '=', $m->title);
if($label == "")
{
$label .= $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= $m->metric['value'];
}
else
{
$label .= '|' . $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= ',' . $m->metric['value'];
}
}
return array('label' => $label, 'data' => $data);
}
public function getMetric($metric, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metric . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
return $XML_object->entry->metric['value'] ? $XML_object->entry->metric['value'] : 0;
}
public function getMetricURI($metric, $uri, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metric . "&dimensions=ga:pagePath&filters=ga:pagePath=" . $uri . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
return $XML_object->entry->metric['value'] ? $XML_object->entry->metric['value'] : 0;
}
}
?>
Pour récupérer une instance de cette classe on appelle la méthode statique instance() :
Ensuite on peut utiliser les méthodes comme dans l’exemple ci-dessous :
$countries = $ga->getDimensionByMetric('visits', 'country', date('Y-m-d', time()));
$visits = $ga->getMetric('visits', date('Y-m-d', time()));
$unique_visits = $ga->getMetric('visitors', date('Y-m-d', time()));
$page_views = $ga->getMetric('pageviews', date('Y-m-d', time()));
- getDimensionByMetric() permet d’effectuer une requête avec un metric et une dimension.
- getMetric() permet d’effectuer une requête avec un metric uniquement.
- getMetricURI() permet d’effectuer une requête avec un metric par rapport à une URI précise.
On passe soit un intervalle (une période), soit une seule date.
Cette classe et ces méthodes sont très perfectibles, mais elles me suffisent amplement pour une intégration basique de Google Analytics. Ceci m’a permis d’avoir le résultat suivant :
L’image ci-dessus présente ma page de statistiques dans ma partie administrateur du blog. On peut voir le nombre de visites au total, le nombre de pages vues et le nombres de visiteurs uniques, le tout sur la journée. J’ai aussi deux graphiques représentant les visites par navigateur et par pays.
L’image ci-dessus représente l’intégration de Google Analytics pour chacun de mes articles. On peut y voir le nombre de fois que cet article a été affiché, le nombre de consultations uniques ainsi que le temps moyen passé sur cet article, le tout sur la journée.
Liens annexes :
http://www.willdurand.fr/api-google-analytics-decouverte-par-l-exemple/
http://www.willdurand.fr/api-google-analytics-round-2-graphiques-et-statistiques-par-page/


















2 commentaires
Salut.
J’arrive un peu tard sur le sujet, mais je souhaitais noter une petite erreur : dans la fonction getMetricURI, l’url devrait comporter un double égal avant la mention de l’uri.
Remplacer :
par :
J’en profite tout de même pour dire merci (c’est la moindre des choses), pour ces 3 billets sur le sujet, qui m’ont bien été utiles
Un trackback
L’en-tête idéal pour vos newsletters…
Votre article est intéressant. J’ai fais un lien vers sa page depuis mon blog
…