php 8.6读取上游sse时,curl回调收到的是任意长度字节块,不能把每次回调当成一条事件。应先按cr、lf或crlf还原文本行,遇到空行再合并多条data字段;没有结束空行的残余事件不派发。以下演示单次连接的数据读取,不实现eventsource自动重连和last-event-id恢复。

PHP手册中的curl_setopt定义
用事件解析器保存跨块状态
SSE按UTF-8编码。解析器只处理data和event字段,忽略注释及本例未使用的id、retry字段;每行和每条事件都有体积上限,防止服务器一直不结束事件而占满内存。
<?php
final class SseReader {
private string $line = '';
private bool $afterCr = false;
private bool $first = true;
private array $data = [];
private string $event = 'message';
private int $bytes = 0;
public function feed(string $chunk): void {
for ($i = 0, $n = strlen($chunk); $i < $n; ++$i) {
$c = $chunk[$i];
if ($this->afterCr && $c === "\n") { $this->afterCr = false; continue; }
$this->afterCr = false;
if ($c === "\r" || $c === "\n") {
$this->process($this->line); $this->line = '';
$this->afterCr = $c === "\r";
} else {
$this->line .= $c;
if (strlen($this->line) > 131072) throw new RuntimeException('SSE行过大');
}
}
}
private function process(string $line): void {
if ($this->first) { $line = preg_replace('/^\xEF\xBB\xBF/', '', $line); $this->first = false; }
if ($line === '') {
if ($this->data !== []) {
echo json_encode(['event' => $this->event, 'data' => implode("\n", $this->data)],
JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), PHP_EOL;
}
$this->data = []; $this->event = 'message'; $this->bytes = 0; return;
}
if ($line[0] === ':') return;
$parts = explode(':', $line, 2);
$value = $parts[1] ?? '';
if (str_starts_with($value, ' ')) $value = substr($value, 1);
if ($parts[0] === 'event') $this->event = $value === '' ? 'message' : $value;
if ($parts[0] === 'data') {
$this->bytes += strlen($value) + 1;
if ($this->bytes > 262144) throw new RuntimeException('SSE事件过大');
$this->data[] = $value;
}
}
}
PHP手册中的curl_exec定义
把cURL字节块交给解析器
将解析器与下面代码放在同一个CLI脚本。上游地址由部署配置提供,只连接可信HTTPS接口,所需鉴权头按该接口文档另行设置,不打印密钥。保持TLS证书验证开启。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
$url = getenv('SSE_ENDPOINT');
if (!is_string($url) || parse_url($url, PHP_URL_SCHEME) !== 'https') {
throw new RuntimeException('需要可信HTTPS上游地址');
}
$reader = new SseReader(); $isSse = false;
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 120,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Accept: text/event-stream'],
CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$isSse): int {
if (str_starts_with($line, 'HTTP/')) $isSse = false;
if (stripos($line, 'Content-Type:') === 0) {
$isSse = strtolower(trim(explode(';', substr($line, 13), 2)[0])) === 'text/event-stream';
}
return strlen($line);
},
CURLOPT_WRITEFUNCTION => static function ($ch, string $chunk) use ($reader, &$isSse): int {
if (!$isSse || curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
throw new RuntimeException('上游未返回有效SSE响应');
}
$reader->feed($chunk); return strlen($chunk);
},
]);
if (curl_exec($curl) === false) throw new RuntimeException(curl_error($curl));不要把连接结束等同于任务完成
WHATWG规定连接结尾未被空行结束的事件应丢弃,本例不会在EOF强制输出残余内容。应用层是否存在“完成”事件或特殊文本,须按上游自己的协议判断;网络超时和HTTP错误不代表业务成功。输出JSON只便于CLI检查,转发给浏览器时应另行实现下游SSE编码及背压。


















