Real-time Data Visualization Using PHP WebSocket and Highcharts

This tutorial explains how to build a real-time data visualization feature by setting up a PHP WebSocket server with Ratchet and displaying live data on the client side using Highcharts, covering environment setup, server and client code, and deployment considerations.

php Courses
php Courses
php Courses
Real-time Data Visualization Using PHP WebSocket and Highcharts

Real-time data visualization refers to displaying server‑sent data instantly in a web application, useful for scenarios such as smart homes, IoT, and financial trading.

1. Implementation Idea

1. Server sends real‑time data to the client. 2. Client receives the data. 3. Client processes the data and converts it into visual charts. 4. Client displays the charts to the user.

The article uses PHP as the server‑side language and Highcharts as the front‑end framework to achieve this workflow.

2. Environment Setup

1. Install PHP and Apache. 2. Install Composer. 3. Use Composer to install the Ratchet framework and ReactPHP library. 4. Create a "phpwebsocket" folder in the web root to store Ratchet source code.

3. Server‑side Code

require __DIR__ . '/phpwebsocket/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new class() implements \Ratchet\MessageComponentInterface {
                private $clients;
                public function __construct() {
                    $this->clients = new \SplObjectStorage;
                }
                public function onOpen(\Ratchet\ConnectionInterface $conn) {
                    $this->clients->attach($conn);
                    echo "New connection! ({$conn->resourceId})
";
                }
                public function onMessage(\Ratchet\ConnectionInterface $from, $msg) {
                    echo "Message received from {$from->resourceId}: $msg
";
                    foreach ($this->clients as $client) {
                        if ($client !== $from) {
                            $client->send($msg);
                        }
                    }
                }
                public function onClose(\Ratchet\ConnectionInterface $conn) {
                    $this->clients->detach($conn);
                    echo "Connection {$conn->resourceId} has disconnected
";
                }
                public function onError(\Ratchet\ConnectionInterface $conn, \Exception $e) {
                    echo "An error has occurred: {$e->getMessage()}
";
                    $conn->close();
                }
            }
        )
    ),
    8080
);
$server->run();

The code creates a WebSocket server on port 8080 and implements four event listeners (onOpen, onMessage, onClose, onError) to manage client connections and broadcast messages.

4. Client Code

The client uses Highcharts to render received data and consists of an HTML page and JavaScript.

4.1 HTML Page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Real-time Chart</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <div id="container"></div>
    <script>
        var chart = Highcharts.chart('container', {
            chart: {
                type: 'spline',
                animation: Highcharts.svg,
                marginRight: 10,
                events: {
                    load: function () {
                        var series = this.series[0];
                        var socket = new WebSocket('ws://localhost:8080');
                        socket.onmessage = function(event) {
                            var data = JSON.parse(event.data);
                            var x = (new Date()).getTime(); // current time
                            var y = data.value; // data value
                            series.addPoint([x, y], true, true);
                        };
                        socket.onerror = function(error) {
                            console.log('WebSocket error');
                        };
                    }
                }
            },
            time: { useUTC: false },
            title: { text: 'Real-time Chart' },
            xAxis: { type: 'datetime', tickPixelInterval: 150 },
            yAxis: {
                title: { text: 'Value' },
                plotLines: [{ value: 0, width: 1, color: '#808080' }]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: { enabled: false },
            exporting: { enabled: false },
            series: [{ name: 'Value', data: [] }]
        });
    </script>
</body>
</html>

The page loads Highcharts and jQuery, creates a spline chart, opens a WebSocket connection to the PHP server, and updates the chart with incoming data points.

4.2 JavaScript Code

var socket = new WebSocket('ws://localhost:8080');

socket.onopen = function(event) {
    console.log('WebSocket open');
};

socket.onerror = function(error) {
    console.log('WebSocket error');
};

setInterval(function() {
    var value = Math.random();
    socket.send(JSON.stringify({value: value}));
}, 1000);

This script establishes the WebSocket connection, logs connection status, handles errors, and sends a random value to the server every second.

Conclusion

By combining a PHP Ratchet WebSocket server with Highcharts on the client, a complete real‑time data visualization system is built; further enhancements such as authentication and data standardization can be added for production use.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendReal-TimeWebSocketPHPData visualizationhighcharts
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.