tags:

views:

87

answers:

4

Let's say file test.php looks like this:

<?php
echo 'Hello world.';
?>

I want to do something like this:

$test = include('test.php');

echo $test;

// Hello world.

Can anyone point me down the right path?

Edit:

My original goal was to pull PHP code intermingled with HTML out of a database and process it. Here's what I ended up doing:

// Go through all of the code, execute it, and incorporate the results into the content
while(preg_match('/<\?php(.*?)\?>/ims', $content->content, $phpCodeMatches) != 0) {
    // Start an output buffer and capture the results of the PHP code
    ob_start();
    eval($phpCodeMatches[1]);
    $output = ob_get_clean();

    // Incorporate the results into the content
    $content->content = str_replace($phpCodeMatches[0], $output, $content->content);
}
+10  A: 

Using output buffering is the best bet.


ob_start();
include 'test.php';
$output = ob_get_clean();

PS: Remember that you can nest output buffers to your hearts content as well if needed.

PHP-Steven
save a line: `$output = ob_get_clean();` ;-)
Philippe Gerber
Awesome, thanks!
Kirk
+3  A: 

You can also have the included file return the output, rather than print it. Then you can grab it into a variable, just like you do in your second example.

<?php
    return 'Hello world.';
?>
Atli
A: 
$test = file_get_contents('test.php');
echo $test; //Outputs "Hello world.";
pnm123
That won't parse the PHP in test.php, just print it. And doing an eval() on the string would be slower than using an include with output buffering.
PHP-Steven
include does exactly the same as file_get_contents + eval do
stereofrog
+1  A: 

test.php

<?php

return 'Hello World';

?>


<?php

$t = include('test.php');

echo $t;

?>

As long as the included file has a return statement it will work.

Galen