How to add something to the top of the PHP output buffer?

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

For example, let's 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 clearing the contents of the browser, how can I add something so that it appears before <p>Start of page.</p> when the page loads?

It sounds simple enough, like moving a pointer to the beginning of an array, but I could not find how to do this with the output buffer.

+4
source share
5 answers

** 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>'; 
+4
source

Use the 2 ob_start and ob_end_flush () commands after what you want to display first, then end the buffer with ob_end_flush when you want to display the rest of the page.

eg:

 ob_start(); ob_start(); echo '<p>Start of page.</p>'; ob_end_flush(); echo '<p>Middle of page.</p>'; echo '<p>End of page</p>'; ob_end_flush(); 
0
source

See the first ob_start parameter (documentation here ), it allows you to provide a callback for a call when the buffer is flushed or flushed . It takes a string as a parameter and displays the string, so it should be easy

 function writeCallback($buffer) { return "Added before " . $buffer; } ob_start("writeCallback"); 
0
source

You can get the contents of the buffer using the ob_get_contents () function

 ob_start(); echo "World! "; $out1 = ob_get_contents(); echo "Hello, ".$out1; 
0
source

Do you want this to be before any conclusion? If so, then you are looking for the auto_prepend_file directive. http://php.net/manual/en/ini.core.php

0
source

All Articles