How to pull a number of visitors?

How to pull a number of visitors using Matomo?
An example of message in PHP:
29 community visitors are considering this booking right now!

without any knowledge about your site: you can probably do it using the API with its segmentation feature: Reporting API Reference: API Reference - Matomo Analytics (formerly Piwik Analytics) - Developer Docs - v5

however, it might be more complex/complicated than doing it with a dedicated script that just maintains a table of counters and reads from it.

2 Likes

Thanks for sharing it. I shall apply and share my experience here.

visting are actually currently visitors not historically. Do you have PHP code?

If we do PHP code, how to pull out visitors if we are using Matomo API:
https://developer.matomo.org/api-reference/reporting-api

An example:

echo $data[0]['visitors'] . " Your visitors are there!";

Is there container script to push ALL VISITORS message using Matomo analytics based on Events as IP address is not important in this case?

ChatGPT says:(I didnt test!)

<?php

// Matomo API URL
$matomoUrl = 'https://your-matomo-url/matomo/';

// Matomo API Token
$token = 'your_api_token';

// Matomo Site ID
$siteId = 1; // Set this to your project's site ID

// API endpoint for real-time visitors (last 30 minutes)
$apiUrl = $matomoUrl . 'index.php?module=API&method=Live.getCounters&idSite=' . $siteId . '&lastMinutes=30&format=JSON&token_auth=' . $token;

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // If SSL is used and you don't have certificates

// Execute the API call and save the response
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Decode the response
$liveData = json_decode($response, true);

// Extract the visitor count from the response
if (isset($liveData[0]['visitors'])) {
    $visitors = $liveData[0]['visitors'];
    echo 'Real-time visitors (last 30 minutes): ' . $visitors;
} else {
    echo 'Could not retrieve real-time visitor data.';
}

?>

Explanation:

  1. $matomoUrl: The base URL of your Matomo installation.
  2. $token: Your API token from Matomo.
  3. $siteId: The ID of the website in Matomo for which you want to retrieve the real-time visitor data.
  4. $apiUrl: The complete URL for the API call to Matomo’s Live API, specifying the last 30 minutes.
  5. cURL: Used to send the API request to Matomo and retrieve the response.
  6. $liveData: The response is decoded from JSON, and the number of visitors in the last 30 minutes is extracted.

This code retrieves the number of visitors active on your site in the last 30 minutes and displays it on your webpage. Make sure cURL is enabled in your PHP setup for this code to work properly.

1 Like