2011-11-15 57 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中......