Kurt Van den Branden Kurt Van den Branden - 2 months ago 19
PHP Question

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?

Answer

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);
    }
?>