我尝试了:
$test = include 'test.php';
但那只是正常地包含了文件
你需要查看输出缓冲函数。
//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;
编辑:
正如Jeremy所指出的,输出缓冲区是堆叠的。因此你理论上可以像这样做:
<?PHP
function return_output($file){
ob_start();
include $file;
return ob_get_clean();
}
$content = return_output('some/file.php');
这应该等同于我更冗长的原始解决方案。
但我并没有费心测试这个。
试试这样做:
ob_start();
include('test.php');
$content = ob_get_clean();
file_get_contents()
函数。
该函数与
file()
类似,但是file_get_contents()
返回文件的字符串。
解决方案 #1: 使用include(类似于函数):[我最好的解决方案]
文件 index.php:
<?php
$bar = 'BAR';
$php_file = include 'included.php';
print $php_file;
?>
文件 included.php:
<?php
$foo = 'FOO';
return $foo.' '.$bar;
?>
<p>test HTML</p>
FOO BAR
,但是注意:它类似于函数,所以返回会将内容传回到变量(上面的<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;
?>
文件 included.php:
<?php
$foo = 'FOO';
print $foo.' '.$bar;
?>
<p>test HTML</p>
如果你使用ob_get_contents()
,它将输出FOO BAR<p>test HTML</p>
两次,请确保使用ob_get_clean()
解决方案 #3: file_get_contents():
文件 index.php:
<?php
$bar = 'BAR';
$test_file = eval(file_get_contents('included.php'));
print $test_file;
?>
文件 included.php:
$foo = 'FOO';
print $foo.' '.$bar;
FOO BAR
,但注意:Include.php不应该有<?php
的开头和结尾标签,因为您要通过eval()运行它。ob_get_contents()
应该改为ob_get_clean()
,否则会输出两次。答案正在相应地进行编辑。 - Duncanmoo'included.php'
)?eval
的参数包含HTML和嵌入式PHP标记,会抛出错误吗?<?php ?>
包围。 - Duncanmooeval
不允许混合使用php和html。另外,回答一下我的问题#2:是的,可以在include之后使用变量,以动态地给出文件名。 - toddmo其他的答案,原因我不知道,都没有达到正确的解决方案。
我建议使用缓冲区,但是你必须在页面结束之前获取内容并清空缓冲区,否则会输出。如果你想使用包含文件的输出,你应该使用op_get_contents()
,它会返回缓冲区内容的字符串。
你也不需要循环遍历包含文件,因为每个文件只会添加到缓冲区(除非你先清空它)。
因此,你可以使用以下代码:
ob_start();
include_once('test.php');
include_once('test2.php');
$contents = ob_get_contents();
ob_end_clean();
file_get_contents
。