我试过了:
$test = include 'test.php';
Run Code Online (Sandbox Code Playgroud)
但那只是正常包含文件
tim*_*dev 30
您将需要查看输出缓冲功能.
//get anything that's in the output buffer, and empty the buffer
$oldContent = ob_get_clean();
//start buffering again
ob_start();
//include file, capturing output into the output buffer
include "test.php";
//get current output buffer (output from test.php)
$myContent = ob_get_clean();
//start output buffering again.
ob_start();
//put the old contents of the output buffer back
echo $oldContent;
Run Code Online (Sandbox Code Playgroud)
编辑:
正如Jeremy指出的那样,输出缓冲区堆栈.所以理论上你可以做以下事情:
<?PHP
function return_output($file){
ob_start();
include $file;
return ob_get_clean();
}
$content = return_output('some/file.php');
Run Code Online (Sandbox Code Playgroud)
这应该等同于我更详细的原始解决方案.
但我没有费心去测试这个.
Bra*_*don 10
尝试类似的东西:
ob_start();
include('test.php');
$content = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
解决方案#1:使用include(像函数一样工作):[我的最佳解决方案]
文件index.php:
<?php
$bar = 'BAR';
$php_file = include 'included.php';
print $php_file;
?>
Run Code Online (Sandbox Code Playgroud)
文件included.php:
<?php
$foo = 'FOO';
return $foo.' '.$bar;
?>
<p>test HTML</p>
Run Code Online (Sandbox Code Playgroud)
这将输出FOO BAR,但
注意:像函数一样工作,所以RETURN将内容传递回变量(<p>test HTML</p>将在上面丢失)
解决方案#2: op_buffer():
文件index.php:
<?php
$bar = 'BAR';
ob_start();
include 'included.php';
$test_file = ob_get_clean(); //note on ob_get_contents below
print $test_file;
?>
Run Code Online (Sandbox Code Playgroud)
文件included.php:
<?php
$foo = 'FOO';
print $foo.' '.$bar;
?>
<p>test HTML</p>
Run Code Online (Sandbox Code Playgroud)
如果你使用ob_get_contents()它会输出FOO BAR<p>test HTML</p> TWICE,请确保你使用ob_get_clean()
解决方案#3: file_get_contents():
文件index.php:
<?php
$bar = 'BAR';
$test_file = eval(file_get_contents('included.php'));
print $test_file;
?>
Run Code Online (Sandbox Code Playgroud)
文件included.php:
$foo = 'FOO';
print $foo.' '.$bar;
Run Code Online (Sandbox Code Playgroud)
这将输出FOO BAR,但注意:<?php当你通过eval()运行时,Include.php不应该有开始和结束标记
| 归档时间: |
|
| 查看次数: |
17105 次 |
| 最近记录: |