Search code examples
phpoutput-buffering

How to prepend something to the beginning of the PHP output buffer?


How do you append something to the beginning of the output buffer?

For example, say you have the following code:

ob_start();

echo '<p>Start of page.</p>';
echo '<p>Middle of page.</p>';
echo '<p>End of page</p>';

Before flushing the contents to the browser, how can I append something so that it appears before <p>Start of page.</p> when the page loads?

It sounds simple enough, like moving the pointer to the beginning of an array, but I couldn't find how to do it with the output buffer.


Solution

  • ** PHP 5.3 **

    ob_start(function($output) {
        $output = '<p>Prepended</p>'.$output;
        return $output;
    });
    
    echo '<p>Start of page.</p>';
    echo '<p>Middle of page.</p>';
    echo '<p>End of page</p>';
    

    ** PHP < 5.3 **

    function prependOutput($output) {
        $output = '<p>Appended</p>'.$output;
        return $output;
    }
    
    ob_start('prependOutput');
    
    echo '<p>Start of page.</p>';
    echo '<p>Middle of page.</p>';
    echo '<p>End of page</p>';