php - 使用ob_start()时无法捕获 echo 或错误

标签 php error-handling

我正在尝试编写一个简单的模板解析对象,并且我的代码效果很好。问题是主页中的任何echo命令或错误都应该由ob_start缓冲。在销毁处触发错误处理路由,并在第52行死亡。但是,此操作永远不会运行。有任何想法吗?

<?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.";   
?>

template-main.html应该具有
<!!--list--!!>

我希望看到的是:
应该保存到文件中,并且永远不会显示在屏幕上。因为这应该存储在对象第51行之后的$ errors中。

我得到的是:Hello World

最佳答案

尝试用ob_end_flush()包围回声。和ob_start();

例如:

ob_end_flush();

# CODE THAT NEEDS IMMEDIATE FLUSHING

ob_start();

来源:How to flush output after each `echo` call?

关于php - 使用ob_start()时无法捕获 echo 或错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811575/

相关文章:

php - 开始使用PHP多维数组将MySQL转JSON中添加数组名

php - Wordpress nginx 重定向循环

php - 使用 apache 通过 php 执行 shell 脚本时,当前用户和 env 用户不匹配

tcp - UDP - 可选校验和

php - 如何在Symfony 4中使用dataTables防止错误 “Invalid JSON response”?

c++ - 在我的C++ CaesarCipher程序中出现错误

javascript - 如何处理响应对象中的错误

php - 将 3 个数据库表连接在一起

php - JavaScript 不工作,没有错误

jquery - 用jQuery逗号分隔的错误列表