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

后端代碼
<?php
// 關(guān)閉輸出緩沖
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
while (ob_get_level()) ob_end_clean(); // 清除所有緩沖層
// 設(shè)置HTTP頭(流式內(nèi)容類型 + 禁用緩存)
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
// 模擬對(duì)話回復(fù)內(nèi)容
$messages = [
"你好!我正在分析您的問題...\n",
"已找到相關(guān)解決方案,請稍等。\n",
"處理完成!以下是詳細(xì)回答:\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服務(wù)器緩沖
usleep(50000); // 50ms延遲模擬打字效果
}
}
// 持續(xù)生成內(nèi)容的例子(如從數(shù)據(jù)庫/API獲?。?
for ($i=1; $i<=5; $i++) {
echo "正在處理第 {$i} 項(xiàng)任務(wù)...\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;
// 將二進(jìn)制數(shù)據(jù)解碼為文本
const text = decoder.decode(value);
// 實(shí)時(shí)追加到頁面
botMessage.innerHTML += text;
messagesContainer.scrollTop = messagesContainer.scrollHeight;
// 繼續(xù)讀取下一塊
return readChunk();
});
}
return readChunk();
})
.catch(console.error);
}
</script>
</body>
</html>
運(yùn)行測試
項(xiàng)目根目錄下打開命令行輸入以下命令,執(zhí)行
php -S 127.0.0.1:6789
打開瀏覽器,輸入 127.0.0.1:6789 訪問Web界面,輸入任意內(nèi)容發(fā)送后,即可看到流式輸出效果
原理解析
1. 什么是流式輸出
流式輸出通常指的是在數(shù)據(jù)生成的同時(shí)逐步發(fā)送到客戶端,而不是等待所有處理完成后再一次性發(fā)送。這在實(shí)時(shí)聊天應(yīng)用或需要逐步顯示結(jié)果的場景中很常見。
2. PHP怎么做到流式輸出
PHP默認(rèn)是緩沖輸出的,也就是說,腳本執(zhí)行完畢后才會(huì)將內(nèi)容發(fā)送到瀏覽器。所以需要調(diào)整輸出緩沖的設(shè)置。比如調(diào)用ob_flush()和flush()來實(shí)時(shí)發(fā)送內(nèi)容。
3. 前端處理數(shù)據(jù)的接收和顯示
前端監(jiān)聽來自服務(wù)器的事件,每次接收到數(shù)據(jù)就更新頁面。本次實(shí)踐通過Fetch讀取流式響應(yīng)體,逐塊處理。
到此這篇關(guān)于PHP+HTML實(shí)現(xiàn)流式輸出效果的示例詳解的文章就介紹到這了,更多相關(guān)PHP HTML流式輸出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
php的webservice的wsdl的XML無法顯示問題的解決方法
本篇文章是對(duì)php的webservice的wsdl的XML無法顯示問題的解決方法進(jìn)行了介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2014-03-03
php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究
這篇文章主要介紹了php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
解決更換PHP5.4以上版本后Dedecms后臺(tái)登錄空白問題的方法
為什么會(huì)出現(xiàn)更換PHP5.4以上版本后Dedecms后臺(tái)登錄空白的情況,本文將給大家詳細(xì)分析,找出真正原因以及解決辦法。2015-10-10
php計(jì)算數(shù)組不為空元素個(gè)數(shù)的方法
本文為大家介紹下php計(jì)算數(shù)組不為空元素個(gè)數(shù)的方法,需要的朋友可以參考下2014-01-01
php cookie 作用范圍–不要在當(dāng)前頁面使用你的cookie
這兩天在調(diào)試bug的時(shí)候遇到了一個(gè)問題,就是頁面莫名其妙的會(huì)跳轉(zhuǎn)到登陸頁面2009-03-03

