[英]PHP delay the output of headers until the entire PHP script has been run?
可以將標頭的輸出延遲到瀏覽器,直到整個php腳本完成執行為止?
一旦第一段代碼從php發送到網絡服務器,就會發送標題。
因此,您可以在腳本結束之前“不回顯任何內容”或use output buffering
來實現相同的功能
這是大多數專業程序員建議的方式,你應該總是這樣做的原因是你可以有效地管理錯誤和錯誤頁面。
如果您的應用程序已經構建為在腳本執行時顯示輸出,那么我建議您從頭開始。
我通常管理輸出的方式是使用小模板的系統,模板的系統不需要解析模板等,只需要傳遞一組數據然后包含所需的模板。
你應該創建一個以$template->set(key[,value = true])
的形式接受數據的類,然后創建一個顯示的函數,例如$template->display(filename)
,當這個函數執行時你應該提取變量,然后包含模板文件,完成后再調用exit(0)
這樣就不再執行代碼了。
一個簡單的模板系統可以這樣:
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);
}
}
然后使用非常簡單:
$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");
您可能還想閱讀我之前回答的以下答案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.