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_replac开发者_运维知识库e($phpCodeMatches[0], $output, $content->content);
}
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.
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.
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.';
?>
$test = file_get_contents('test.php');
echo $test; //Outputs "Hello world.";
精彩评论