Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you render a PHP file into a variable?

Tags:

php

If I have a hello.php file like this:

Hello, <?php echo $foo; ?>!

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

$text = renderPhpToString('hello.php', array('foo'=>'World'));

and end up with

$text == 'Hello, World!'

Is this possible with standard PHP 5? Obviously I want more complex templates with loops and so forth..

like image 280
danb Avatar asked Apr 17 '09 19:04

danb


People also ask

How PHP files can be accessed?

PHP Open File - fopen() A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.

How do I call a PHP page from another PHP page?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.


1 Answers

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.

like image 73
Gumbo Avatar answered Oct 03 '22 00:10

Gumbo