Can you render a PHP file into a variable?

前端 未结 5 1919
孤城傲影
孤城傲影 2020-12-28 08:51

If I have a hello.php file like this:

Hello, !

I would like to do something like this in some php code:

         


        
5条回答
  •  囚心锁ツ
    2020-12-28 09:35

    You could use some function like this:

    function renderPhpToString($file, $vars=null)
    {
        if (is_array($vars) && !empty($vars)) {
            extract($vars);
        }
        ob_start();
        include $file;
        return ob_get_clean();
    }
    

    It uses the output buffer control function ob_start() to buffer the following output until it’s returned by ob_get_clean().

    Edit    Make sure that you validate the data passed to this function so that $vars doesn’t has a file element that would override the passed $file argument value.

提交回复
热议问题