English 中文(简体)
Get the Results of an Include in a String in PHP?
原标题:
  • 时间:2009-11-28 23:55:10
  •  标签:
  • php
  • include

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);
}
最佳回答

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. ;
?>




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签