php ob_start() 修复之前输出的标签
我最近刚刚开始摆弄输出缓冲,似乎遇到了障碍。我的网站使用一个模板系统来加载 html 页眉/页脚和正确的内容模板。问题是 html 标头是在加载的第一个模板中设置的。因此,当(如果)加载另一个包含标头(存储在字符串 $headers 中)的模板时,它不会将它们添加到标头中。我创建了一种真正草率的方法来做到这一点,我正在寻找更好地处理这个问题的建议。
index.php
ob_start('ob_html_headers');
回调函数
function ob_html_headers($buffer)
{
global $headers;
return str_replace('</head>', $headers.'</head>', $buffer);
}
如有任何帮助,我们将不胜感激。
I just recently started toying with output buffering and seem to have run into a roadblock. My website utilizes a template system that loads html header/footer and the correct content template. Problem is the html headers are set in the first template loaded. So when (if) another template is loaded that contains headers (stored in a string $headers) it won't add them to the header. I have created a real sloppy way of doing this, I am looking for suggestions on to better handle this.
index.php
ob_start('ob_html_headers');
the callback function
function ob_html_headers($buffer)
{
global $headers;
return str_replace('</head>', $headers.'</head>', $buffer);
}
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,有趣的问题。如果您试图按照我的想法去做,那么您最好建立每个部分要发送的数据,然后回显就结束了。如果您还不想将所有
echo
转换为 $str .= ,则可以嵌套ob_start
。基本上,您似乎想要做的是允许稍后的信息影响早期的输出,最好的方法是构建一个表示您的页面的结构(不用担心几个字符串数组就足够了),然后“渲染”当你知道一切都需要去哪里时,它就在最后。
Hmmm, interesting question. If you are trying to do what I think you are, you'd probably be better off building up the data to be sent per-section, then echoing is all out the end. You can nest
ob_start
if you don't want to go about converting all yourecho
s to $str .= quite yet.Basically what you seem to want to do is to allow later information to affect earlier output, the best way to do that is build a structure (don't worry a few arrays of strings could suffice) that represents your page, then "render" it at the end when you know where everything needs to go.
我不明白为什么“标题”存储在模板中。
据我了解模板,模板中使用的任何动态值都必须在业务逻辑部分中定义(并且很可能从数据库中获取)。
这样你就不会遇到这样的问题。
I don't understand why "headers" being stored in the template.
As far as I understand templating, whatever dynamic value used in the template, have to be defined in the business logic part (and most likely taken from the database).
This way you will experience no problem like this.