ob_clean
Эта функция очищает содержимое выходного буфера, не отправляя его в браузер.
Эта функция не уничтожает буфер вывода, как это делает ob_end_clean() .
Буфер вывода должен запускаться функцией ob_start() с флагом PHP_OUTPUT_HANDLER_CLEANABLE. Иначе ob_clean() не сработает.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Смотрите также
- ob_flush() — Сбросить (отправить) буфер вывода
- ob_end_flush() — Сбросить (отправить) буфер вывод и отключить буферизацию вывода
- ob_end_clean() — Очистить (стереть) буфер вывода и отключить буферизацию вывода
User Contributed Notes 5 notes
@cornel: It’s easy enough to say «Don’t do that» when you think you’ve got the person right in front of you. But one doesn’t always have the original coder, or even one of a dozen of the original coders. Are you really suggesting that it would be wrong to use this function as a band-aid when the alternative may be looking through hundreds of source files you didn’t write for errors you didn’t introduce?
To your point, though, it is (or should be) a commonly accepted best practice to not put closing PHP tags at the end of files. When, however, enforcing that would take a time machine, it’s appropriate to use ob_clean() as a band-aid to make dynamically generated images work as expected.
I find this function incredibly useful when manipulating or creating images in php (with GD).
I spent quite a while searching through a large number of included files to find where I had a undesired space after php’s ending tag — as this was causing all my images on the fly to break due to output already being set. Even more annoying was that this was not caught not php’s error reporting so there was no reference to the problem line(s) in my log file. I don’t know why error reporting wouldn’t catch this since it was set to accept warnings, and the same thing had been caught in the past.
Nevertheless, I never did find the line(s) that were adding extra spaces or new lines before my images were being generated, but what I did instead was add this handy function right before my image manipulation code and right after the include/require code.
// require some external library files
require ( «lib/somelibrary.php» );
require ( «lib/class/someclass.php» );
// clean the output buffer
ob_clean ();
// simple test image
header ( «Content-type: image/gif» );
$im = imagecreate ( 100 , 50 );
imagegif ( $im );
imagedestroy ( $im );
?>
While this may seem trivial a trivial use of the function, it in fact is incredibly useful for insuring no extra spaces or new lines have already been output while making images in php. As many of you probably already know, extra lines, spacing and padding that appears prior to image-code will prevent the image from being created. If the file «lib/somelibrary.php» had so much as an extra new line after the closing php tag then it would completely prevent the image from working in the above script.
If you work on an extremely large project with a lot of source and required files, like myself, you will be well-advised to always clear the output buffer prior to creating an image in php.
ob_end_clean
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.
The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.
Parameters
This function has no parameters.
Return Values
Returns true on success or false on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
Errors/Exceptions
If the function fails it generates an E_NOTICE .
Examples
The following example shows an easy way to get rid of all output buffers:
Example #1 ob_end_clean() example
See Also
- ob_start() — Turn on output buffering
- ob_get_contents() — Return the contents of the output buffer
- ob_flush() — Flush (send) the output buffer
User Contributed Notes 12 notes
Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression
ini_set ( ‘zlib.output_compression’ , ‘1’ );
?>
ob_end_clean(); in this example will throw the error.
Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.
Because there is no way of removing the callback from the OB once you’ve set it, the only way to stop the callback function from having any effect is to do something like:
<?php
$ignore_callback = false ;
ob_start ( ‘my_callback’ );
.
if( $need_to_abort ) <
$ignore_callback = true ;
ob_end_clean ();
.
>
function my_callback (& $buffer ) <
if( $GLOBALS [ ‘ignore_callback’ ]) <
return «» ;
>
.
>
?>
If there is no confidence about output buffering (enabled or not),
you may try these guards:
while ( ob_get_level () !== 0 ) <
ob_end_clean ();
>
while ( ob_get_length () !== false ) <
ob_end_clean ();
>
Keep in mind that mrfritz379’s example (#49800) is just an example. You can achieve that example’s result in a more efficient manner without using output buffering functions:
echo «<p>Search running. Please be patient. . .»;
$output = «<p>FileList: </p>\n»;
if (is_dir($dir)) <
$dh = opendir($dir);
while (($fd = readdir($dh)) != false) <
echo » .»;
$output .= $fd;
>
>
echo «</br>Search Complete!</p>\n»;
echo $output;
In addition to John Smith’s comment (#42939), ob_gzhandler() may still set the HTTP header «Content-Encoding» to «gzip» or «deflate» even if you call ob_end_clean(). This will cause a problem in the following situation:
1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Echo «New content»;
In the above case, the browser may receive the «Content-Encoding: gzip» HTTP header and attempts to decompress the uncompressed «New content». The browser will fail.
In the following situation, this behaviour will go unnoticed:
1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo «New content»;
This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().
A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().
You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:
$mtime=filemtime($_SERVER[«SCRIPT_FILENAME»])-date(«Z»);
$gmt_mtime = date(‘D, d M Y H:i:s’, $mtime) . ‘ GMT’;
if(isset($headers[«If-Modified-Since»])) <
if ($headers[«If-Modified-Since»] == $gmt_mtime) <
header(«HTTP/1.1 304 Not Modified»);
ob_end_clean();
exit;
>
>
$size=ob_get_length();
header(«Last-Modified: «.$gmt_mtime);
header(«Content-Length: $size»);
ob_end_flush();
Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.
You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there’s no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.
Notice that ob_end_clean() does discard headers.
If you would like to clear the output buffer, but not the headers (because you use firephp for example. ), than this is the solution:
$headers = array();
if ( ! headers_sent () ) <
$headers = apache_response_headers ();
>
if ( !empty( $headers ) ) <
foreach ( $headers as $name => $value ) <
header ( » $name : $value » );
>
>
.
?>
I use it in a general exception handler in a web application, where I clear the buffer (but not the debug-info-containing headers), and send a 500 error page with readfile().
This may be posted elsewhere, but I haven’t seen it.
To run a progress indicator while the program is running without outputting the output buffer, the following will work:
echo «<p>Search running. Please be patient. . .»;
$output = «<p>FileList: </p>\n»;
if (is_dir($dir)) <
$dh = opendir($dir);
while (($fd = readdir($dh)) != false) <
echo » .»;
ob_start();
echo $fd;
$output .= ob_get_contents();
ob_end_clean();
>
>
echo «</br>Search Complete!</p>\n»;
echo $output;
The program will continue to print the » .» without printing the file list. Then the «Search Complete» message will print followed by the buffered file list.
About the previous comment:
You can also relay on ETag and simply use time()
<?php
$time = time ();
$mins = 1 ;
if (isset( $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ]) and str_replace ( ‘»‘ , » , $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ])+( $mins * 60 ) > $time )
<
header ( ‘HTTP/1.1 304 Not Modified’ );
exit();
>
else
<
header ( ‘ETag: «‘ . $time . ‘»‘ );
>
echo ‘Caching for ‘ , $mins * 60 , ‘secs<br/>’ , date ( ‘G:i:s’ );
?>
In reference to <geoff at spacevs dot com> where he states, «If you call ob_end_clean in a function registered with ‘register_shutdown_function’, it is too late, any buffers will have already been sent out to the client.», here is a workaround I came up with.
function ClearBuffer ( $Buffer ) <
return «» ;
>
function Shutdown () <
ob_start ( «ClearBuffer» );
>
?>
This will wipe out all the contents of the output buffer as it comes in. Basically its the same as «STDOUT > /dev/null».
Как очистить веб-страницу с помощью PHP?
Я пытаюсь очистить веб-страницу и проанализировать с нее некоторые данные. Но каждый раз, когда я пытаюсь очистить, я получаю только заголовок HTTP-ответа . Вот мой код, который я использовал для получения данных с сайта ..
Но это дает мне ошибку, указанную ниже ..
Так может ли кто-нибудь помочь мне с тем, где я ошибаюсь в этом
2 ответа
Заголовок 302 — это информация о перенаправлении.
Если вы ищете ScreenScrape с помощью PHP, я успешно сделал это с помощью библиотеки PHP Simple HTML DOM Parser. Это очень просто и легко использовать. Я знаю, что сайт выглядит немного устаревшим, но мой прошлогодний код все еще работает. Еще не было ошибки CRON.