2011-11-15 56 views
1

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

回答

3

的我能想到的办法夫妇:

  1. 保持一个变量(称为像$内容),并且每次调用使用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(); 
    
+0

为什么迪你做'file_put_contents('log.html',$ content。 ob_get_contents());'而不是'file_put_contents('log.html',$ content); – Nyxynyx

+0

您仍然在最终缓冲区中有一些内容。另外,你可以把“$ content。= ob_get_contents();”如果你做了“file_put_contents('log.html',$ content);” – landons

+0

很好,明白,谢谢! – Nyxynyx

2

你也可以使用ob_get_contents()一路走来,将它保存到一个变量,然后进入文件和OutputStream中......