ob_start
(PHP 4, PHP 5)
ob_start — Включение буферизации вывода
Описание
Эта функция включает буферизацию вывода. Если буферизация вывода активна, вывод скрипта не высылается (кроме заголовков), а сохраняется во внутреннем буфере.
Содержимое этого внутреннего буфера может быть скопировано в строковую переменную, используя ob_get_contents(). Для вывода содержимого внутреннего буфера следует использовать ob_end_flush(). В качестве альтернативы можно использовать ob_end_clean() для уничтожения содержимого буфера.
Некоторые web-сервера (например Apache) изменяют рабочую директорию скрипта, когда вызывается callback-функция. Вы можете вернуть ее назад, используя chdir(dirname($_SERVER['SCRIPT_FILENAME'])) в callback-функции.
Буферы вывода помещаются в стэк, то есть допускается вызов ob_start() после вызова другой активной ob_start(). При этом необходимо вызывать ob_end_flush() соответствующее количество раз. Если активны несколько callback-функций, вывод последовательно фильтруется для каждой из них в порядке вложения.
Список параметров
-
output_callback
-
В качестве необязательного параметра может быть указана функция
output_callback
. Эта функция принимает строку как параметр и должна возвращать строку. Функция будет вызвана при сбросе (отправке) буфера вывода или очистке (вместе с ob_flush(), ob_clean() или аналогичной функцией) или когда буфер выводится в браузер в конце запроса. При вызовеoutput_callback
, она принимает содержимое буфера вывода как параметр и возвращает новое содержимое, которое и отправляется в браузер. Еслиoutput_callback
не является вызываемой функцией, то эта функция вернетFALSE
.Если callback-функции передано 2 параметра, то второй параметр рассматривается как битовое значение состоящее из
PHP_OUTPUT_HANDLER_*
constants.Если
output_callback
вернетFALSE
, то оригинальная информация отправится в браузер без изменений.Параметр
output_callback
может быть игнорирован передачей значенияNULL
.ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() и ob_start() не могут вызываться из callback-функций, так как их поведение непредсказуемо. Если вы хотите удалить содержимое буфера, то верните "" (пустую строку) из callback-функции. Вы так же не можете вызывать функции print_r($expression, true) или highlight_file($filename, true) из callback-функций буферизации вывода.
Замечание:
В PHP 4.0.4 функция ob_gzhandler() была введена для облегчения отправки gz-кодированных данных web-браузерам, поддерживающим сжатые web-страницы. ob_gzhandler() определяет тип кодировки содержимого, принимаемый браузером, и возвращает вывод соответствующим образом.
-
chunk_size
-
Если передан не обязательный параметр
chunk_size
, то буфер буден сброшен после любого вывода превышающего или равного по размеруchunk_size
. Значение по умолчанию 0 означает, что функция вывода будет вызвана, когда буфер будет закрыт.До PHP 5.4.0, значение 1 было специальным значением, которое устанавливало параметр chunk_size в 4096.
-
erase
-
Если не обязательный параметр
erase
установлен вFALSE
, то буфер не будет удален пока скрипт не закончит работу. Это приведет к тому, что попытка сбросить или очистить буфер выдаст уведомление и вернетFALSE
при вызове.
Возвращаемые значения
Возвращает TRUE
в случае успешного завершения или FALSE
в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
5.4.0 | Параметр chunk_size, установленный в 1, теперь приводит к выводу по 1 байту в выходной буфер. |
4.3.2 |
Функция вернет FALSE в случае, если
output_callback не сможет быть выполнена.
|
4.2.0 |
Добавлен параметр erase .
|
Примеры
Пример #1 Пример callback-функции, определенной пользователем
<?php
function callback($buffer)
{
// заменить все яблоки апельсинами
return (str_replace("яблоки", "апельсины", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>Это все равно что сравнить яблоки и апельсины.</p>
</body>
</html>
<?php
ob_end_flush();
?>
Результат выполнения данного примера:
<html> <body> <p>Это все равно что сравнить апельсины и апельсины.</p> </body> </html>
Смотрите также
- ob_get_contents() - Возвращает содержимое буфера вывода
- ob_end_clean() - Очищает (стирает) буфер вывода и отключает буферизацию вывода
- ob_end_flush() - Сброс (отправка) буфера вывода и отключение буферизации вывода
- ob_implicit_flush() - Функция включает/выключает неявный сброс
- ob_gzhandler() - callback-функция, используемая для gzip-сжатия буфера вывода при вызове ob_start
- ob_iconv_handler() - Преобразует символы из текущей кодировки в кодировку выходного буфера
- mb_output_handler() - Callback-функция, преобразующая кодировку символов в выходном буфере
- ob_tidyhandler() - Функция обратного вызова ob_start для восстановление буфера
Коментарии
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)
<pre><?php
ob_start(); // start output buffer 1
echo "a"; // fill ob1
ob_start(); // start output buffer 2
echo "b"; // fill ob2
$s1 = ob_get_contents(); // read ob2 ("b")
ob_end_flush(); // flush ob2 to ob1
echo "c"; // continue filling ob1
$s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
ob_end_flush(); // flush ob1 to browser
// echoes "b" followed by "abc", as supposed to:
echo "<HR>$s1<HR>$s2<HR>";
?></pre>
... at least works on Apache 1.3.28
Nandor =)
You can use PHP to generate a static HTML page. Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand. A "cron" job can execute the PHP script to create the HTML page. For example:
<?php // CREATE index.html
ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
$page = ob_get_contents();
ob_end_clean();
$cwd = getcwd();
$file = "$cwd" .'/'. "index.html";
@chmod($file,0755);
$fw = fopen($file, "w");
fputs($fw,$page, strlen($page));
fclose($fw);
die();
?>
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.
Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;
In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.
If you need a scenario like the one above, using an "inner envelope" will help:
ob_start();
ob_start(); // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;
In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
Hello firends
ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).
The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.
These are two usages of ob_start():
1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user
If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.
With Regards, Hossein
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!
Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:
$handlers = ob_list_handlers();
while ( ! empty($handlers) ) {
ob_end_clean();
$handlers = ob_list_handlers();
}
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.
If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.
For instance:
<?php
ob_start();
myClass::renderPng(); //header("Content-Type: image/png"); in here
$pngString = ob_get_contents();
ob_end_clean();
?>
will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.
You need to set the correct image type (text/html) manually in this case.