EventSource 是一种浏览器端的技术,它允许服务器向客户端推送实时更新。在 PHP 中,你可以使用 EventSource 来实现服务器端的推送功能。以下是一个简单的示例,展示了如何使用 PHP EventSource 进行实时数据更新:
首先,创建一个 PHP 文件(例如:event_source.php),并添加以下代码:<?phpheader('Content-Type: text/event-stream');header('Cache-Control: no-cache');// 获取当前时间并格式化为 ISO8601 格式$time = date(DATE_ISO8601);// 发送事件数据echo "data: {$time}\n\n";flush();?>这个 PHP 脚本会设置正确的响应头,然后发送一个包含当前时间的事件数据。flush() 函数用于清空输出缓冲区,确保数据立即发送到客户端。
index.html),并添加以下代码:<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>EventSource Example</title></head><body> <h1>EventSource Example</h1> <p id="time"></p> <script> // 创建一个 EventSource 对象,连接到 event_source.php const eventSource = new EventSource('event_source.php'); // 监听服务器发送的消息 eventSource.onmessage = function (event) { // 获取事件数据 const data = event.data; // 更新页面上的时间显示 document.getElementById('time').innerText = 'Server time: ' + data; }; </script></body></html>这个 HTML 文件创建了一个 EventSource 对象,连接到我们刚刚创建的 PHP 脚本。当服务器发送消息时,我们会更新页面上的时间显示。
index.html。你应该能看到实时更新的服务器时间。注意:确保你的 Web 服务器支持 PHP,并且已经正确配置。此外,由于 EventSource 是基于 HTTP 长连接的,因此在某些情况下可能会遇到跨域问题。你需要确保服务器允许跨域请求,或者将客户端和服务器部署在同一个域名下。


