ob_start()是否用于输出缓冲,以便头被缓冲而不发送到浏览器?我说的有道理吗?如果不是,那么为什么我们要使用ob_start()?
当前回答
我使用这个,所以我可以用很多HTML跳出PHP,但不渲染它。它使我不必将它存储为禁用IDE颜色编码的字符串。
<?php
ob_start();
?>
<div>
<span>text</span>
<a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>
而不是:
<?php
$content = '<div>
<span>text</span>
<a href="#">link</a>
</div>';
?>
其他回答
这个函数不仅仅用于头文件。你可以用它做很多有趣的事情。例子:你可以把你的页面分成几个部分,像这样使用:
$someTemplate->selectSection('header');
echo 'This is the header.';
$someTemplate->selectSection('content');
echo 'This is some content.';
您可以捕获此处生成的输出,并将其添加到布局中的两个完全不同的位置。
我喜欢:
ob_start();
echo("Hello there!");
$output = ob_get_clean(); //Get current buffer contents and delete current output buffer
以下内容在现有的答案中没有提及: 缓冲区大小配置 HTTP报头 和嵌套。
ob_start的缓冲区大小配置:
ob_start(null, 4096); // Once the buffer size exceeds 4096 bytes, PHP automatically executes flush, ie. the buffer is emptied and sent out.
上面的代码提高了服务器性能,因为PHP将发送更大的数据块,例如,4KB(如果没有ob_start调用,PHP将向浏览器发送每个echo)。
如果你开始缓冲没有块大小(即。一个简单的ob_start()),那么页面将在脚本的末尾发送一次。
输出缓冲不会影响HTTP报头,它们以不同的方式处理。然而,由于缓冲,你可以在输出发送后发送头,因为它仍然在缓冲区中。
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
这里有很好的解释:https://phpfashion.com/everything-about-output-buffering-in-php
你搞反了。Ob_start不缓冲头文件,它缓冲内容。使用ob_start允许您将内容保存在服务器端缓冲区中,直到准备好显示它为止。
这是常用的,这样页面就可以在他们已经“发送”了一些内容之后发送标题(例如,在渲染页面的中途决定重定向)。
这里公认的答案描述了ob_start()做什么-而不是为什么使用它(这是被问到的问题)。
如别处所述,ob_start()创建一个缓冲区,输出写入其中。
但是没有人提到在PHP中可以堆叠多个缓冲区。看到ob_get_level()。
至于为什么....
Sending HTML to the browser in larger chunks gives a performance benefit from a reduced network overhead. Passing the data out of PHP in larger chunks gives a performance and capacity benefit by reducing the number of context switches required Passing larger chunks of data to mod_gzip/mod_deflate gives a performance benefit in that the compression can be more efficient. buffering the output means that you can still manipulate the HTTP headers later in the code explicitly flushing the buffer after outputting the [head]....[/head] can allow the browser to begin marshaling other resources for the page before HTML stream completes. Capturing the output in a buffer means that it can redirected to other functions such as email, or copied to a file as a cached representation of the content
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号