5

そのため、 、、 のob_start()ように別のバッファ関数が呼び出されるまで、出力をキャプチャすることになっています。ob_get_clean()ob_get_contents()ob_get_flush()

ただし、バッファー リーダー内で例外がスローされると、リーダーを停止し、出力をキャプチャし続ける代わりにエコーすることで、リーダーに影響を与えます。これは私が防ぎたいものです。

これが私のスクリプトだとしましょう:

<?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.

私は何を間違っていますか、解決策はありますか?

4

3 に答える 3

9

私の推測では、catch ブロック内であっても、出力バッファリングはまだアクティブです。ただし、スクリプトはアクティブな出力バッファリングで終了するため、PHP は自動的に出力バッファを表示します。

ob_clean()したがって、例外ハンドラー内で呼び出すことができます。

于 2013-07-14T04:57:41.573 に答える
1

次のようなことができます。

<?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();
?>
于 2013-07-14T05:17:13.007 に答える