php ob_start() 修复之前输出的标签

发布于 2025-01-01 05:56:32 字数 479 浏览 0 评论 0原文

我最近刚刚开始摆弄输出缓冲,似乎遇到了障碍。我的网站使用一个模板系统来加载 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓦然回首 2025-01-08 05:56:32

嗯,有趣的问题。如果您试图按照我的想法去做,那么您最好建立每个部分要发送的数据,然后回显就结束了。如果您还不想将所有 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 your echos 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.

暮色兮凉城 2025-01-08 05:56:32

我不明白为什么“标题”存储在模板中。

据我了解模板,模板中使用的任何动态值都必须在业务逻辑部分中定义(并且很可能从数据库中获取)。

这样你就不会遇到这样的问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文