API Google Analytics – Une classe PHP5 et des résultats d’intégration

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.

class GAnalytics
{
  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() :

$ga = GAnalytics::instance();

Ensuite on peut utiliser les méthodes comme dans l’exemple ci-dessous :

$navigateurs = $ga->getDimensionByMetric('visits', 'browser', date('Y-m-d', time()));
$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/

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • FriendFeed
  • LinkedIn
  • MySpace
  • Netvibes
  • PDF
  • Ping.fm
  • RSS
  • Technorati
  • viadeo FR
  • Wikio
  • Yahoo! Buzz

Related Posts

Cet article a été publié dans Ancien blog avec les mots-clefs : , , , , , , . Bookmarker le permalien. Laisser un commentaire ou faire un trackback : URL de trackback.

Laisser un commentaire

Votre e-mail ne sera jamais publié ni communiqué. Les champs obligatoires sont indiqués par *

*
*

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting