使用谷歌分析来跟踪PHP API的使用情况


Use Google Analytics to track usage of PHP API

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

我已经尝试https://developers.google.com/analytics/devguides/collection/other/mobileWebsites做服务器端,但由于我的API不能打开任何图像,它将无法工作。有什么想法吗?

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

如果你已经更新到Universal Analytics(新的Google Analytics),你可以直接从PHP生成事件或页面浏览量

Google已经创建了测量协议,它基本上是一组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;
}

使用方法如下:

AnalyticsDoHit("UA-XXXXXX-X", "http://www.AutomatedEmailParser.com/EmailAndParser_setup.msi", "EmailAndParser_setup.msi");

看看Universal Analytics https://developers.google.com/analytics/devguides/collection/protocol/v1/或http://code.google.com/p/php-ga/用于在PHP中模拟ga.js服务器端

我使用的是Google Analytics Measurement Protocol for PHP库,它有许多框架的包装器,如Laravel, Yii等。

您可以测量API使用情况、电子商务事件或任何您需要的东西。你也可以发送异步请求