2013-07-14 60 views
2

因此ob_start()應該捕獲輸出,直到另一個緩衝區函數被調用,如ob_get_clean(),ob_get_contents(),ob_get_flush()當發生錯誤時ob_start被中斷

但是,當緩衝區讀取器內部拋出異常時,它會通過停止它並回顯輸出而不是繼續捕獲它來影響讀取器。這是我想要防止的。

比方說這是我的腳本:

<?php 
    error_reporting(0); 
    try { 
     ob_start(); 
      echo "I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions"; 
      $unlink = unlink('some file that does not exist'); 
      if(!$unlink) throw new Exception('Something really bad happen.', E_ERROR); //throwing this exception will effect the buffer 
     $output = ob_get_clean(); 
    } catch(Exception $e) { 
     echo "<br />Some error occured: " . $e->getMessage(); 
     //print_r($e); 
    } 
?> 

這個腳本會輸出:

I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions 
Some error occurred: Something really bad happen. 

當它的假設只是打印

Some error occurred: Something really bad happen. 

我在做什麼錯,是有解決方案嗎?

+0

嘗試移動'嘗試... catch'塊'ob_start()'之外。 – vee

+0

@vinodadhikary感謝您的評論,這可以工作,但會導致錯誤消息得到緩衝。我不希望這種情況發生。 – Junior

回答

5

我的猜測是,即使在你的catch塊中,輸出緩衝仍然是活動的。但是,腳本以激活的輸出緩衝結束,所以PHP會自動顯示輸​​出緩衝區。

因此,您可以嘗試在異常處理程序中調用ob_clean()

+1

你是絕對正確的,我不敢相信我沒有想到!非常感謝。 – Junior

0

你可以做這樣的事情:

<?php 
    error_reporting(0); 
    $currentBuffers = ''; 
    try { 
     ob_start(); 
     echo "I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions"; 
     $unlink = unlink('some file that does not exist'); 
     if(!$unlink) throw new Exception('Something really bad happen.', E_ERROR); //throwing this exception will effect the buffer 
     $output = ob_get_clean(); 
    } catch(Exception $e) { 
     $currentBuffers = ob_get_clean(); 
     ob_end_clean(); // Let's end and clear ob... 
     echo "<br />Some error occured: " . $e->getMessage(); 
     //print_r($e); 
    } 

    // Do something to $currentBuffer 

    // Maybe start again? 
    ob_start(); 
    echo "foo"; 
    $currentBuffers .= ob_get_clean(); 
    //echo $currentBuffers; 
     ob_end_clean(); 
?> 
相關問題