ob_get_level in PHP

ob_get_level — Return the nesting level of the output buffering mechanism

ob_get_level(): int

Returns the nesting level of the output buffering mechanism.

Example

This can be used to handle exceptions properly when using output buffering for rendering a view which may or may not be using output buffering

<?php

function getView($view)
{
    $level = ob_get_level();

    ob_start();

    try
    {
        include $view;
    }

    catch (Exception $e)
    {
        while (ob_get_level() > $level)
        {
            ob_end_clean();
        }

        throw $e;
    }

    return ob_get_clean();
}

Leave a Comment