使用Google Analytics跟踪PHP API的使用情况

Mol*_*tra 6 php google-analytics google-analytics-api

我的网络服务器上有一个访问网站数据库中数据的API.我想弄清楚如何使用谷歌分析来跟踪API使用情况.访问API响应的客户端将无法执行javascript.

我已尝试https://developers.google.com/analytics/devguides/collection/other/mobileWebsites来执行服务器端,但由于MY API无法打开任何图片,因此无法使用.有什么想法吗?

API示例是http://www.serviidb.com/api/video.

car*_*357 6

如果您已更新为Universal Analytics(新的Google Analytics),则可以直接从PHP生成事件或综合浏览量.

Google已经创建了Measurement协议,该协议基本上是一组http请求,其中一些参数包含您要跟踪的内容.我将在此处粘贴我在自己网站中使用的代码来跟踪下载.

要跟踪任何内容,您只需使用自己的参数调用AnalyticsDoHit():

// Create a page view directly from PHP. No javascript.
function AnalyticsDoHit($tid, $slug, $title)
{
// Standard params
$v   = 1;
$cid = ParseOrCreateAnalyticsCookie();

// Send PageView hit
$data = array(
    'v' => $v,
    'tid' => $tid,
    'cid' => $cid,
    't' => 'pageview',
    'dt' => $title,
    'dp' => $slug
);

$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
file_get_contents($getString); // do the https request
}


// Gets the current Analytics session identifier or create a new one
// if it does not exist
function ParseOrCreateAnalyticsCookie()
{
if (isset($_COOKIE['_ga']))
    {
    // An analytics cookie is found
    list($version, $domainDepth, $cid1, $cid2) = preg_split('[\.]', $_COOKIE["_ga"], 4);
    $contents = array(
        'version' => $version,
        'domainDepth' => $domainDepth,
        'cid' => $cid1 . '.' . $cid2
    );
    $cid      = $contents['cid'];
    }
else
    {
    // no analytics cookie is found. Create a new one
    $cid1 = mt_rand(0, 2147483647);
    $cid2 = mt_rand(0, 2147483647);

    $cid = $cid1 . '.' . $cid2;
    setcookie('_ga', 'GA1.2.' . $cid, time() + 60 * 60 * 24 * 365 * 2, '/');
    }
return $cid;
}
Run Code Online (Sandbox Code Playgroud)

使用方法如下:

AnalyticsDoHit("UA-XXXXXX-X", "http://www.AutomatedEmailParser.com/EmailAndParser_setup.msi", "EmailAndParser_setup.msi");
Run Code Online (Sandbox Code Playgroud)