1. Go to this page and download the library: Download alexwestergaard/php-ga4 library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// se AlexWestergaard\PhpGa4\Exception;
use AlexWestergaard\PhpGa4\Analytics;
use AlexWestergaard\PhpGa4\Event;
use AlexWestergaard\PhpGa4\Item;
// pseudo function, make your own logic here
$visitors = getVisitorsWithEvents();
foreach ($visitors as $visitor) {
// Group of events, perhaps need logic to change from json or array to event objects
// Maybe its formatted well for the > ConvertHelper::parseEvents([...]) < helper
$groups = $visitor['events'];
// If gtag.js, this can be the _ga or _gid cookie
// This can be any kind of session identifier
// Usually derives from $_COOKIE['_ga'] or $_COOKIE['_gid'] set by GTAG.js
$client = $visitor['client_id'];
// load logged in user/visitor
// This can be any kind of unique identifier, readable is easier for you
// Just be wary not to use GDPR sensitive information
$user = $visitor['user_id'];
$userParameters = $visitor["user_parameters"]
// Render events grouped on time (max offset is 3 days from NOW)
foreach ($groups as $time => $data) {
try {
$analytics = Analytics::new($measurementId, $apiSecret)
->setClientId($client)
->setTimestampMicros($time);
if ($user !== null) {
$analytics->setUserId($user);
}
// pseudo logic for adding user parameters
$analytics->addUserParameter(...$userParameters);
// pseudo logic for adding events
$analytics->addEvent(...$data['events']);
// send events to Google Analytics
$analytics->post();
} catch (Exception\Ga4Exception $exception) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
ExceptionTrail(function(Exception $e) {/*...*/}, $exception)
}
}
}
// pseudo function to trail the exception tree
function ExceptionTrail(callable $handler, Exception $e) {
$handler($e);
$prev = $e->getPrevious();
if ($prev instanceof Exception) {
ExceptionTrail($handler, $prev);
}
}
// EventHelper implements AlexWestergaard\PhpGa4\Facade\Type\EventType
class ExampleEvent extends AlexWestergaard\PhpGa4\Helper\EventHelper
{
// variables should be nullable as unset() will set variable as null
protected null|mixed $my_variable;
protected null|mixed $my_,
];
}
public function getRequiredParams(): array
{
return [
'my_