使用 PHP 进行流式打印

发布于 2024-10-12 11:28:37 字数 468 浏览 2 评论 0原文

我编写了一个 PHP 脚本,它向搜索引擎发出请求,访问提供的结果,从结果中提取一些详细信息,然后以更有用的形式打印它们。

一切都运行良好,但我偶然发现,在等待数据流式传输时调用 echo 或 print 也会导致输出流式传输。具体来说,有多个页面的结果,因此我访问第一页,读入并重新打印内容,然后转到下一页,在等待下一页加载时,上一页的内容在中变得可见浏览器。

我不明白的是为什么这种情况会如此不一致。有时,在移动到下一页之前,会恰好打印一页,有时会打印更少,有时会打印更多。然后,当我之后做基本相同的事情时(在每个结果指向的页面中读取),输出几乎根本不流式传输,每分钟左右重新绘制一次。

我使用 file_get_contents($url) 检索内容,并调用其中包含 echo 的函数来打印到目前为止已加载的内容。这种流式打印行为是浏览器的功能吗?与我用 PHP 编写的内容无关吗?如果不能的话,怎样才能更好的控制呢?

I've written a PHP script that makes a request to a search engine, accesses the served results, extracts some details from the results and then prints them in a more useful form.

It all works well, but something I've discovered by accident is that calling echo or print while waiting for data to be streamed in can result in the output being streamed as well. Specifically, there are multiple pages of results, so I access the first page, read in and re-print the content, then move on to the next page, and while waiting for that next page to load, the previous page's content becomes visible in the browser.

What I don't understand is why this happens so inconsistently. Sometimes exactly one page will be printed before moving onto the next page, sometimes less and sometimes more. Then when I do basically the same thing afterwards (read in the page each result points to), the output is barely streamed at all, being redrawn every minute or so.

I'm using file_get_contents($url) to retrieve the content, and calling a function with an echo in it to print what has been loaded so far. Is this streaming print behaviour a feature of the browser and independent of what I write in PHP? If not, how can it be controlled better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥枳 2024-10-19 11:28:38

最简单的解决方法是使用输出缓冲。基本思想是在脚本开头调用 ob_start() ,然后在您希望将页面内容发送到客户端时调用 ob_end_flush() 。这样做将保存所有输出,直到您希望程序发送它为止。

The easiest fix is to use output buffering. The basic idea is to call ob_start() at the beginning of your script and then call ob_end_flush() when you want the pages content to be sent to the client. Doing this will save all of your output until you want your program to send it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文