How to add google analytics event via php?

by edmond_brakus , in category: Third Party Scripts , a day ago

How to add google analytics event via php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , an hour ago

@edmond_brakus 

To add a Google Analytics event via PHP, you can use the Measurement Protocol provided by Google Analytics. Here is a basic example of how you can send an event using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
$trackingId = 'UA-XXXXX-Y'; // Your Google Analytics tracking ID
$clientId = '123456789.987654321'; // A unique client ID

$data = array(
    'v' => 1, // API Version
    'tid' => $trackingId, // Tracking ID
    'cid' => $clientId, // Client ID
    't' => 'event', // Hit type
    'ec' => 'Category', // Event Category
    'ea' => 'Action', // Event Action
    'el' => 'Label', // Event Label
    'ev' => 1, // Event Value
);

$url = 'https://www.google-analytics.com/collect';

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => http_build_query($data),
    ),
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === false) {
    echo 'Error sending event to Google Analytics';
} else {
    echo 'Event sent successfully';
}
?>


Replace UA-XXXXX-Y with your Google Analytics tracking ID, and 123456789.987654321 with a unique client ID. You can customize the event category, action, label, and value as needed.


You can call this PHP script whenever you want to send an event to Google Analytics. Make sure to include the script on pages where you want to track events.