PHP+HTML實現(xiàn)流式輸出效果的示例詳解
效果演示

后端代碼
<?php
// 關閉輸出緩沖
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
while (ob_get_level()) ob_end_clean(); // 清除所有緩沖層
// 設置HTTP頭(流式內(nèi)容類型 + 禁用緩存)
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
// 模擬對話回復內(nèi)容
$messages = [
"你好!我正在分析您的問題...\n",
"已找到相關解決方案,請稍等。\n",
"處理完成!以下是詳細回答:\n"
];
// 流式輸出每條消息
foreach ($messages as $msg) {
// 逐字輸出(可選)
// $length = strlen($msg);
$length = mb_strlen($msg);
for ($i=0; $i<$length; $i++) {
// echo $msg[$i];
$char = mb_substr($msg, $i, 1, 'UTF-8');
echo $char;
ob_flush(); // 刷新PHP緩沖
flush(); // 刷新Web服務器緩沖
usleep(50000); // 50ms延遲模擬打字效果
}
}
// 持續(xù)生成內(nèi)容的例子(如從數(shù)據(jù)庫/API獲取)
for ($i=1; $i<=5; $i++) {
echo "正在處理第 {$i} 項任務...\n";
ob_flush();
flush();
sleep(1);
}
前端代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>智能客服系統(tǒng)</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}
.chat-container {
width: 800px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
.messages {
height: 500px;
overflow-y: auto;
border-bottom: 1px solid #ddd;
padding-bottom: 10px;
}
.message {
margin: 10px 0;
}
.user {
text-align: right;
}
.bot {
text-align: left;
}
.input-container {
display: flex;
margin-top: 10px;
}
.input-container input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
.input-container button {
padding: 10px 20px;
border: none;
background-color: #007bff;
color: #fff;
border-radius: 5px;
cursor: pointer;
}
.input-container button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="messages" id="messages" style="white-space: pre-wrap;"></div>
<div class="input-container">
<input type="text" id="userInput" placeholder="輸入消息...">
<button onclick="sendMessage()">發(fā)送</button>
</div>
</div>
<script>
function sendMessage() {
const userInput = document.getElementById('userInput').value;
if (userInput.trim() === '') return;
document.getElementById('userInput').value = '';
const messagesContainer = document.getElementById('messages');
const userMessage = document.createElement('div');
userMessage.className = 'message user';
userMessage.textContent = userInput;
messagesContainer.appendChild(userMessage);
fetch('stream.php')
.then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
const botMessage = document.createElement('div');
botMessage.className = 'message bot';
messagesContainer.appendChild(botMessage);
function readChunk() {
return reader.read().then(({ done, value }) => {
if (done) return;
// 將二進制數(shù)據(jù)解碼為文本
const text = decoder.decode(value);
// 實時追加到頁面
botMessage.innerHTML += text;
messagesContainer.scrollTop = messagesContainer.scrollHeight;
// 繼續(xù)讀取下一塊
return readChunk();
});
}
return readChunk();
})
.catch(console.error);
}
</script>
</body>
</html>
運行測試
項目根目錄下打開命令行輸入以下命令,執(zhí)行
php -S 127.0.0.1:6789
打開瀏覽器,輸入 127.0.0.1:6789 訪問Web界面,輸入任意內(nèi)容發(fā)送后,即可看到流式輸出效果
原理解析
1. 什么是流式輸出
流式輸出通常指的是在數(shù)據(jù)生成的同時逐步發(fā)送到客戶端,而不是等待所有處理完成后再一次性發(fā)送。這在實時聊天應用或需要逐步顯示結果的場景中很常見。
2. PHP怎么做到流式輸出
PHP默認是緩沖輸出的,也就是說,腳本執(zhí)行完畢后才會將內(nèi)容發(fā)送到瀏覽器。所以需要調(diào)整輸出緩沖的設置。比如調(diào)用ob_flush()和flush()來實時發(fā)送內(nèi)容。
3. 前端處理數(shù)據(jù)的接收和顯示
前端監(jiān)聽來自服務器的事件,每次接收到數(shù)據(jù)就更新頁面。本次實踐通過Fetch讀取流式響應體,逐塊處理。
到此這篇關于PHP+HTML實現(xiàn)流式輸出效果的示例詳解的文章就介紹到這了,更多相關PHP HTML流式輸出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
原生JavaScript+PHP多圖上傳實現(xiàn)示例
這篇文章主要為大家介紹了原生JavaScript+PHP多圖上傳實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
php利用scws實現(xiàn)mysql全文搜索功能的方法
這篇文章主要介紹了php利用scws實現(xiàn)mysql全文搜索功能的方法,可通過scws分詞插件的擴展來實現(xiàn)MySQL全文搜索功能,是非常實用的技巧,需要的朋友可以參考下2014-12-12
php eval函數(shù)用法 PHP中eval()函數(shù)小技巧
本函式可將字符串之中的變量值代入,通常用在處理數(shù)據(jù)庫的數(shù)據(jù)上2012-10-10

