开发者

PHP delay the output of headers until the entire PHP script has been run?

It is possible to delay the output of the headers to the browser until the ent开发者_开发知识库ire php script has finished executing?


The headers will be sent once the first piece of code is sent from php to the webserver.

So you can just "not echo anything" until the end of the script or use output buffering to achieve the same thing


This is the way most professional programmers would advise, the reasons you should always do it this way is that you can manage errors and error pages effectively.

If your application is already built to display output as the script is executed then i would advise you to start from scratch.

the way I usually manage output is with a small template's system, the template's system does not have to parse templates etc, it just needs to be passed a set of data and then include the required template.

you should create a class that acccepts data in the form of $template->set(key[,value = true]) and then a function that would display such as $template->display(filename), when this function executes you should extract the variables and then include the template file, after that has been done you then call exit(0) so no further code is executed.

a simple template system can be like so:

class Template
{
    private $_data = array();

    public function set($key,$value = true)
    {
        $this->_data[$key] = $value;
    }

    public function display($template)
    {
        //Check template exuists
        extract($this->_data);
        require_once $template;
        exit(0);
    }
}

then use pretty simply like so:

$template = new Template();
$template->set("title","Practical home Page");
$template->set("header","My Home Page");

$lists = array(
    array(
        "value" => "list item 1",
        "id" => "list_item_1",
        "class" => "item"
    ),
    array(
        "value" => "list item 2",
        "id" => "list_item_2",
        "class" => "item"
    )
);

$template->set("menu",$lists);
$template->display("templates/homepage.php");

you may also would like to read the following answer I had answered previously!

PHP Looping Template Engine - From Scratch

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜