Search code examples
phpoutput-buffering

php ob_start() fix previously outputted tags


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.


Solution

  • 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.