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/ */
// Manual setting of each event
$event->setLanguage(string $var);
$event->setPageLocation(string $var);
$event->setPageReferrer(string $var);
$event->setPageTitle(string $var);
$event->setScreenResolution(string $var);
// Fillable for multiple events
$eventPage = AlexWestergaard\PhpGa4\Helper\EventParamsHelper();
$event->setEventPage($eventPage);
use AlexWestergaard\PhpGa4\Exception;
use AlexWestergaard\PhpGa4\Analytics;
use AlexWestergaard\PhpGa4\Event;
use AlexWestergaard\PhpGa4\Item;
// rhaps need logic to change from json or array to event objects
// Maybe its formatted well for the > ConvertHelper::parseEvents([...]) < helper
$groups = $collection['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
$visitor = $collection['session_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 = $collection['user_id'];
// Render events grouped on time (max offset is 3 days from NOW)
foreach ($groups as $time => $data) {
try {
$analytics = Analytics::new($measurementId, $apiSecret)
->setClientId($visitor)
->setTimestampMicros($time);
if ($user !== null) {
$analytics->setUserId($user);
}
$analytics->addUserParameter(...$data['userParameters']); // pseudo logic for adding user parameters
$analytics->addEvent(...$data['events']); // pseudo logic for adding events
$analytics->post(); // send events to Google Analytics
} catch (Exception\Ga4Exception $exception) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
}
}
use AlexWestergaard\PhpGa4\Helper\ConvertHelper;
use AlexWestergaard\PhpGa4\Exception;
use AlexWestergaard\PhpGa4\Analytics;
use AlexWestergaard\PhpGa4\Event;
// (Exception\Ga4Exception $exception) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
// 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_