我想寫一個簡單的模板解析對象,我的代碼工作得很好。問題是主頁面中的任何echo命令或者應該由ob_start緩衝。觸發破壞時的錯誤處理路由並在線52上死亡。但是這不會運行。有任何想法嗎?使用ob_start()時無法捕獲回顯或錯誤()
<?php
define('ERROR_FOLDER', 'includes/error/');
define('HTML_FOLDER', 'includes/pages/');
class HTML{
/*
Takes a template file and replaces all instances of <!--VARNAME--> with the value inputed.
All values should be strings.
*/
private $template;
private $vars; //array of user defined variables
function __construct($filePath=''){
//stop writing anything to the page-html-output
ob_start();
//read contents of template
$this->template=file_get_contents(HTML_FOLDER.$filePath);
}
function __destruct() {
echo $this->execute();
}
function getCode() {
return $this->execute();
}
public function get($var) {
return $this->vars[$var];
}
public function set($var,$value) {
$this->vars[$var]=$value;
}
public function append($var,$value) {
$this->vars[$var].=$value;
}
/* ********************************************************************************************************
* Private Functions *
******************************************************************************************************** */
private function execute() {
//handel any errors
$errors=ob_get_contents();
if (strlen($errors>0)) {
echo $errors;die();
//create error file
//name: date_time_random_pageName
$fileName=DateTime::format("Y-m-d_H-i-s-u").'_'.rand(10000,99999).'_'.strtok($_SERVER["REQUEST_URI"],'?').'.txt';
$errorMessage='Error For: ' . $_SERVER[REQUEST_URI] . "\r\n" . $errors;
file_put_contents(ERROR_FOLDER.$fileName, $errorMessage);
}
//erase any error messages
ob_end_clean();
//get template
$html=$this->template;
//create search arrays
$from=array();
$to=array();
foreach ($this->vars as $key=>$value) {
$from[]='<!!--'.$key.'--!!>';
$to[]=$value;
}
//replace any vars added
$html=str_replace($from,$to,$html);
//minimize html text adapted from http://stackoverflow.com/questions/6225351/how-to-minify-php-page-html-output
$from = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s', // removes comments
'/<!!--.*?--!!>|\t|(?:\r?\n[ \t]*)+/s' // removes unused vars
);
$to = array(
'>',
'<',
'\\1',
'',
''
);
$html = preg_replace($from, $to, $html);
return $html;
}
}
?>
這裏是一個測試腳本
<?php
require_once "includes/HTML.php";
$page=new HTML('template-main.html');
$page->set('list','Hello World');
echo "should get saved to file and never show up on screen.";
?>
模板main.html中應該有
<!!--list--!!>
我希望看到的是: 應該得到保存到文件,從不露面在屏幕上。因爲這應該存儲在對象的第51行之後的$ errors中。
我得到的是:你好世界
我不希望任何東西被寫入用戶直到對象被破壞。主程序的任何Echo命令都應視爲錯誤。 –
如果您通過ob_end_flush更改ob_end_clean,該怎麼辦? 編輯:ob_end_clean只清除緩衝區,它ne nevers做任何事情 ,而ob_end_flush在沖洗它之前打印它。 – SamyQc
ob_get_contents()更高的幾行是假設得到它但沒有。我不想打印它。 –