PHP.mk документација

ob_start

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.ob-start.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.ob-start.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ob_start

Референца за `function.ob-start.php` со подобрена типографија и навигација.

function.ob-start.php

ob_start

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_startВклучи баферирање на излез

= NULL

ob_start(?callable $callback = null, int $chunk_size = 0, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS): bool

Вклучи баферирање на излезот Што е бафериран излез? Оваа функција ќе го вклучи баферирањето на излезот. Додека баферирањето на излезот е активно, не се испраќа излез од скриптата, наместо тоа излезот се складира во внатрешен бафер. Видете

точно кој излез е засегнат. ob_start() Баферите за излез може да се наслојуваат, односно, Вгнездување на бафери за излез за повеќе детали.

Константи за известување за грешки Бафери на излез на ниво корисник може да се повика додека друг бафер е активен. Ако се активни повеќе бафери за излез, излезот се филтрира последователно низ секој од нив по редослед на вгнездување. Видете

Параметри

callback

Опционален callback callable за детален опис на баферите за излез. null.

callback може да се специфицира. Исто така може да се заобиколи со поминување

се повикува кога баферот за излез се испушта (испраќа), чисти или кога баферот за излез се испушта на крајот од скриптата. callback Сигнатурата на

handler(string $buffer, int $phase = ?): string
buffer
е како што следува:
phase
Битмаска од PHP_OUTPUT_HANDLER_* constants . Види Знаменца предадени на ракувачи со излез за повеќе детали.

Враќа callback returns false Содржина на баферот за излез. Вредности на враќање на ракувачот со излез за повеќе детали.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

содржината на баферот се враќа. Видете ob_clean(), ob_end_clean(), ob_end_flush(), ob_flush(), ob_get_clean(), ob_get_flush(), ob_start().

Константи за известување за грешки Ракувачи со излез and Работа со ракувачи со излез Повикување на која било од следниве функции од внатрешноста на ракувач со излез ќе резултира со фатална грешка: callbackза повеќе детали за

chunk_size

s (ракувачи со излез). chunk_size Ако опционалниот параметар chunk_sizeсе помине, баферот ќе се испушти по секој блок од код што резултира со излез што предизвикува должината на баферот да биде еднаква или поголема од 0 . Стандардната вредност Големина на бафер за повеќе детали.

flags

На flags значи дека целиот излез се баферира додека баферот не се исклучи. Видете флаери за контрола на баферот . Види Операции дозволени на бафери за повеќе детали.

Секој флаер контролира пристап до сет од функции, како што е опишано подолу:

Константа Функции
PHP_OUTPUT_HANDLER_CLEANABLE ob_clean()
PHP_OUTPUT_HANDLER_FLUSHABLE ob_flush()
PHP_OUTPUT_HANDLER_REMOVABLE ob_end_clean(), ob_end_flush(), ob_get_clean(), ob_get_flush()

Забелешка: Пред PHP 8.4.0, параметарот flags можеше да го постави флаери за статус на излезниот ракувач исто така.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Примери

Пример #1 Пример на кориснички дефинирана функција за повик

<?php

function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush
();

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

Пример #2 Креирање на неуништив излезен бафер

<?php

ob_start
(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE);

?>

Види Исто така

  • ob_get_contents() - Врати ги содржините на излезниот бафер
  • ob_end_clean() Исчисти (избриши) ја содржината на активниот излезен бафер и исклучи го
  • ob_end_flush() Испразни (испрати) ја вратената вредност на активниот ракувач со излез и исклучи го активниот излезен бафер
  • ob_implicit_flush() - Вклучи/исклучи имплицитно исфрлање
  • ob_gzhandler() - ob_start функција за повик за gzip излезен бафер
  • ob_iconv_handler() - Конвертирај кодирање на знаци како ракувач на излезниот бафер
  • mb_output_handler() - Функција за повик конвертира кодирање на знаци во излезниот бафер
  • ob_tidyhandler() - ob_start функција за повик за поправка на баферот

Белешки од корисници 6 белешки

Реј Пасер (Paseur ... ImagineDB.com)
21 години пред
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();
?>
net_navard на yahoo точка com
19 години пред
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
ed.oohay (a) suamhcs_rodnan
пред 22 години
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 =)
Ашер Хаиг (ahaig at ridiculouspower dot com)
пред 18 години
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();
}
Крис
пред 15 години
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.
Throwable::getTraceAsString()
20 години пред
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.