Tuesday, December 17, 2013

How to clear all previous output and echo in php ?

Function of the Day: ob_clean()

http://www.php.net/manual/en/function.ob-clean.php

This function will be very useful if you want to clear all previous output ( for example, all previous echo ).

For example, if we are writing a function which returns json formatted value or echoing image data with content type image/jpeg, We should make sure that no other data is echoed before that. When working on a cms or framework with larger code, Its possible that somewhere some values could be echoed. Even Its possible to have empty space echoed. In such scenarios, We can use use this function to clear all the output.

For example when you run the below code

<?
echo "This is usual first output";
ob_clean();
echo "But This will be first output."
?>

You will not see the "This is usual first output" in the browser. You will see "But This will be first output".

1 comment: