gpt4 book ai didi

php - ob_flush 不丢弃缓冲区

转载 作者:行者123 更新时间:2023-11-28 05:05:40 27 4
gpt4 key购买 nike

我有一个需要几分钟才能完成处理的 PHP 脚本。当页面仍在加载时,我想在可用时显示部分 PHP 输出,这可以使用 ob_start()ob_flush() 来完成。

在整个脚本执行完毕后,我想从一开始就将所有 PHP 输出保存到一个 HTML 文件中。这可以使用 ob_start()file_put_contents("log.html", ob_get_contents());

来完成

问题:但是,因为我们一直在调用 ob_flush(),所以出现了用 file_put_contents() 保存的最终文件分成不同的文件。我怀疑这与在调用 file_put_contents() 之前调用 ob_start() 清除缓冲区有关,但为什么它不只是保存最终之间的输出ob_flush()file_put_contents() 到文件,而是保存几个不同的文件? (我可能错了,单独的部分文件可能是由于脚本的部分执行)

换句话说,如何在执行长脚本时显示 PHP 输出,并将所有 PHP 输出保存到单个 HTML 文件中?

PHP 代码

// Start the buffering
ob_start();

......

ob_flush();

......

ob_flush();

......

file_put_contents("log.html", ob_get_contents());

最佳答案

我能想到的几种方法:

  1. 保留一个变量(称为 $content 之类的东西),并在每次调用 ob_flush() 时追加当前缓冲区:

    $content = '';
    ...
    $content .= ob_get_contents();
    ob_flush();
    ...
    $content .= ob_get_contents();
    ob_flush();
    ...
    file_put_contents('log.html', $content . ob_get_contents());
    ob_flush();
  2. 使用 fopen():

    $fp = fopen('log.html', 'w+');
    ...
    fwrite($fp, ob_get_contents());
    ob_flush();
    ...
    fwrite($fp, ob_get_contents());
    ob_flush();
    ...
    fwrite($fp, ob_get_contents());
    fclose($fp);
    ob_flush();

关于php - ob_flush 不丢弃缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com