发生错误时ob_start被中断

时间:2013-07-14 04:53:28

标签: php buffer

所以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.

我做错了什么,有解决方案吗?

2 个答案:

答案 0 :(得分:7)

我的猜测是,即使在catch块内,输出缓冲仍然有效。但是,脚本以活动输出缓冲结束,因此PHP会自动显示输​​出缓冲区。

因此,您可以尝试在异常处理程序中调用ob_clean()

答案 1 :(得分: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();
?>
相关问题