Kurt Van den Branden
Kurt Van den Branden

Reputation: 12953

How to include google analytics in a php JSON encode result?

I have a php page which encodes an array into a JSON-object or JSONP-callback and simply echoes the result. Because this will become a standalone page that will be accessed directly, I would like to gather insights and include google analytics.

The JSON encode php page:

<?php
    $arr = array('country' => 'United States', 'city' => 'New York');

    if(isset ($_GET['jsonp'])) {
        echo $_GET['jsonp'] . '(' . json_encode($arr) . ')';
    } 
    else {
        echo json_encode($arr);
    }
?>

The jQuery decode part:

<script>
    $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=callback') 
         .done (function(location)
         {
             $('#country').html(location.country);
             $('#city').html(location.city);            
         });
</script>

Google guidelines suggest to create a separate php file which contains the javascript tracking code, and include it in all the php pages you want to track. Something like:

<?php include_once("analyticstracking.php") ?>

This way, the tracker works, but when trying to decode the generated JSON object, the JQuery part breaks on a syntax error, caused by the injected tracker script. The php encode page echoes the tracker script too, which produces a useless JSON result.

Any suggestions?

Upvotes: 4

Views: 895

Answers (4)

Kurt Van den Branden
Kurt Van den Branden

Reputation: 12953

The answer of Eike pointed me in the right direction, therefore +1 for his answer, but I had to use cURL instead of fopen().

My complete working solution:

<?php

    $curl_handle=curl_init();
    curl_setopt($curl_handle, CURLOPT_URL,'http://www.google-analytics.com/collect/v=1&tid=UA-xxxxxxx-1&cid=555&t=pageview&dp=%2Fgeoip.php');
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Geoip tracker');
    $query = curl_exec($curl_handle);
    curl_close($curl_handle);

    $arr = array('country' => 'United States', 'city' => 'New York');

    if(isset ($_GET['jsonp'])) {
        echo $_GET['jsonp'] . '(' . json_encode($arr) . ')';
    } 
    else {
        echo json_encode($arr);
    }
?>

Upvotes: 1

Eike Pierstorff
Eike Pierstorff

Reputation: 32770

I'm not sure if I understand your problem correctly, but you could always do a call to Google Analytics with serverside code via the measurement protocol:

$url = "v=1&t=pageview&tid=UA-39221247-1&cid=5555&dp=%2Fmy%2Fpage";
fopen($url);

Where "v" is the version, "tid" the account number, "cid" the client id and "dp" a document path for your page.

That way there will be no tracking code in the parsed output that would break the jQuery code.

If you want to aggregate individual views into a session you need to maintain the cid between call yourself.

Note that this does not mix very well with the Javascript based tracking (even if you use a client id from an existing ga cookie it would start a new session within GA).

Upvotes: 2

Marco V
Marco V

Reputation: 2653

Could you not load it like this in the footer?

$( document ).ready(function() {
    $("analytics-tracking").load('analyticstracking.php');
});

Upvotes: 1

JP. Aulet
JP. Aulet

Reputation: 4398

I guess that is all fine with your google analytics part, jquery breaks because you return at getJson a not json value, in the if() part you return something like:

callback('country' => 'United States', 'city' => 'New York');

Not a valid json, the else part is fine, you should echo the same in the 2 parts.

Upvotes: 0

Related Questions