【问题标题】:Ob_flush without discarding bufferOb_flush 不丢弃缓冲区
【发布时间】:2011-11-15 12:58:32
【问题描述】:

我有一个 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());

【问题讨论】:

    标签: php html codeigniter


    【解决方案1】:

    我能想到的几种方法:

    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();
      

    【讨论】:

    • 你为什么用file_put_contents('log.html', $content . ob_get_contents());而不是`file_put_contents('log.html', $content);
    • 最终缓冲区中仍有一些内容。或者,您可以输入“$content .= ob_get_contents();”如果您执行“file_put_contents('log.html', $content);”
    【解决方案2】:

    您也可以一路使用ob_get_contents(),将其保存到变量中,然后保存到文件和输出流中...

    【讨论】:

      【解决方案3】:

      您可以获取缓冲区内容,并通过调用ob_get_contents 将其存储在一个变量中。

      你读过manual吗?

      【讨论】:

        猜你喜欢
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多