What is ob_start() function in php?

how to use ob_start() function in php?

ob_start - Turn on output buffering

bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]] )

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Warning : - Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

ob_start() used for output buffering so that the headers are buffered and not sent to the browser?

ob_get_contents

ob_get_contents ? Return the contents of the output buffer

string ob_get_contents ( void )
Gets the contents of the output buffer without clearing it.

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

Output :-

string(6) "Hello "
string(11) "Hello World"

ob_end_clean

ob_end_clean ? Clean (erase) the output buffer and turn off output buffering

bool ob_end_clean ( void )
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

ob_flush

ob_flush ? Flush (send) the output buffer

void ob_flush ( void ) This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.






Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here