• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    PHP+HTML实现流式输出效果的示例详解

    发布者: 山止川行 | 发布时间: 2025-6-14 13:10| 查看数: 43| 评论数: 0|帖子模式

    效果演示



    后端代码
    1. <?php
    2. // 关闭输出缓冲
    3. ini_set('output_buffering', 'off');
    4. ini_set('zlib.output_compression', false);
    5. while (ob_get_level()) ob_end_clean(); // 清除所有缓冲层

    6. // 设置HTTP头(流式内容类型 + 禁用缓存)
    7. header('Content-Type: text/plain; charset=utf-8');
    8. header('Cache-Control: no-cache');
    9. header('X-Accel-Buffering: no');

    10. // 模拟对话回复内容
    11. $messages = [
    12.     "你好!我正在分析您的问题...\n",
    13.     "已找到相关解决方案,请稍等。\n",
    14.     "处理完成!以下是详细回答:\n"
    15. ];

    16. // 流式输出每条消息
    17. foreach ($messages as $msg) {
    18.     // 逐字输出(可选)
    19.     // $length = strlen($msg);
    20.     $length = mb_strlen($msg);
    21.     for ($i=0; $i<$length; $i++) {
    22.         // echo $msg[$i];
    23.         $char = mb_substr($msg, $i, 1, 'UTF-8');
    24.         echo $char;
    25.         ob_flush(); // 刷新PHP缓冲
    26.         flush();    // 刷新Web服务器缓冲
    27.         usleep(50000); // 50ms延迟模拟打字效果
    28.     }
    29. }

    30. // 持续生成内容的例子(如从数据库/API获取)
    31. for ($i=1; $i<=5; $i++) {
    32.     echo "正在处理第 {$i} 项任务...\n";
    33.     ob_flush();
    34.     flush();
    35.     sleep(1);
    36. }
    复制代码
    前端代码
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6.     <title>智能客服系统</title>
    7.     <style>
    8.         body {
    9.             font-family: Arial, sans-serif;
    10.             display: flex;
    11.             justify-content: center;
    12.             align-items: center;
    13.             height: 100vh;
    14.             margin: 0;
    15.             background-color: #f4f4f9;
    16.         }
    17.         .chat-container {
    18.             width: 800px;
    19.             background-color: #fff;
    20.             border-radius: 10px;
    21.             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    22.             padding: 20px;
    23.         }
    24.         .messages {
    25.             height: 500px;
    26.             overflow-y: auto;
    27.             border-bottom: 1px solid #ddd;
    28.             padding-bottom: 10px;
    29.         }
    30.         .message {
    31.             margin: 10px 0;
    32.         }
    33.         .user {
    34.             text-align: right;
    35.         }
    36.         .bot {
    37.             text-align: left;
    38.         }
    39.         .input-container {
    40.             display: flex;
    41.             margin-top: 10px;
    42.         }
    43.         .input-container input {
    44.             flex: 1;
    45.             padding: 10px;
    46.             border: 1px solid #ddd;
    47.             border-radius: 5px;
    48.         }
    49.         .input-container button {
    50.             padding: 10px 20px;
    51.             border: none;
    52.             background-color: #007bff;
    53.             color: #fff;
    54.             border-radius: 5px;
    55.             cursor: pointer;
    56.         }
    57.         .input-container button:hover {
    58.             background-color: #0056b3;
    59.         }
    60.     </style>
    61. </head>
    62. <body>
    63. <div class="chat-container">
    64.     <div class="messages" id="messages" style="white-space: pre-wrap;"></div>
    65.     <div class="input-container">
    66.         <input type="text" id="userInput" placeholder="输入消息...">
    67.         <button onclick="sendMessage()">发送</button>
    68.     </div>
    69. </div>

    70. <script>
    71.     function sendMessage() {
    72.         const userInput = document.getElementById('userInput').value;
    73.         if (userInput.trim() === '') return;
    74.         document.getElementById('userInput').value = '';

    75.         const messagesContainer = document.getElementById('messages');
    76.         const userMessage = document.createElement('div');
    77.         userMessage.className = 'message user';
    78.         userMessage.textContent = userInput;
    79.         messagesContainer.appendChild(userMessage);


    80.         fetch('stream.php')
    81.             .then(response => {
    82.                 const reader = response.body.getReader();
    83.                 const decoder = new TextDecoder('utf-8');

    84.                 const botMessage = document.createElement('div');
    85.                 botMessage.className = 'message bot';
    86.                 messagesContainer.appendChild(botMessage);

    87.                 function readChunk() {
    88.                     return reader.read().then(({ done, value }) => {
    89.                         if (done) return;
    90.                         // 将二进制数据解码为文本
    91.                         const text = decoder.decode(value);
    92.                         // 实时追加到页面
    93.                         botMessage.innerHTML += text;
    94.                         messagesContainer.scrollTop = messagesContainer.scrollHeight;
    95.                         // 继续读取下一块
    96.                         return readChunk();
    97.                     });
    98.                 }
    99.                 return readChunk();
    100.             })
    101.             .catch(console.error);
    102.     }
    103. </script>
    104. </body>
    105. </html>
    复制代码
    运行测试

    项目根目录下打开命令行输入以下命令,执行
    1. php -S 127.0.0.1:6789
    复制代码
    打开浏览器,输入
    1. 127.0.0.1:6789
    复制代码
    访问Web界面,输入任意内容发送后,即可看到流式输出效果

    原理解析

    1. 什么是流式输出
    流式输出通常指的是在数据生成的同时逐步发送到客户端,而不是等待所有处理完成后再一次性发送。这在实时聊天应用或需要逐步显示结果的场景中很常见。
    2. PHP怎么做到流式输出
    PHP默认是缓冲输出的,也就是说,脚本执行完毕后才会将内容发送到浏览器。所以需要调整输出缓冲的设置。比如调用ob_flush()和flush()来实时发送内容。
    3. 前端处理数据的接收和显示
    前端监听来自服务器的事件,每次接收到数据就更新页面。本次实践通过Fetch读取流式响应体,逐块处理。
    到此这篇关于PHP+HTML实现流式输出效果的示例详解的文章就介绍到这了,更多相关PHP HTML流式输出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/program/339718iw0.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表