How to include google analytics in php JSON encoding result?

I have a php page that encodes an array into a JSON object or JSONP callback and just echoes the result. Since this will become a separate page that will be directly accessed, I would like to receive information and enable google analytics.

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

Part of jQuery decoding:

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

Google recommends creating a separate php file containing the javascript tracking code and including it in all the php pages you want to track. Sort of:

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

, , JSON JQuery , script. php encode - script, JSON.

?

+4
4

, +1 , cURL fopen().

:

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

?

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

, , Google Analytics :

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

"v" - , "tid" , "cid" "dp" .

, , jQuery.

, cid .

, Javascript ( ga cookie, GA).

+1

, Google, jquery breaks, getJson json-, if() - :

callback ('' = > '', '' = > '-');

Invalid json, the else part is ok, you have to repeat the same thing in two parts.

0
source

All Articles