PHP Eval that evaluates HTML & PHP

前端 未结 5 718
北海茫月
北海茫月 2020-12-06 01:22

I\'m messing around with templating and I\'ve run into a situation where I need to echo to the browser a template that contains html & php. How do I evaluate the PHP and

5条回答
  •  醉话见心
    2020-12-06 02:14

    Do not read the file, but include it and use output bufferig to capture the outcome.

    ob_start();
    include 'main.php';
    $content = ob_get_clean();
    
    // process/modify/echo $content ...
    

    Edit

    Use a function to generate a new variable scope.

    function render($script, array $vars = array())
    {
        extract($vars);
    
        ob_start();
        include $script;
        return ob_get_clean();
    }
    
    $test = 'one';
    echo render('foo.php', array('test' => 'two'));
    echo $test; // is still 'one' ... render() has its own scope
    

提交回复
热议问题