【发布时间】:2010-01-27 20:58:24
【问题描述】:
我试过了:
$test = include 'test.php';
但这只是正常包含文件
【问题讨论】:
-
你能再详细点吗?
-
你想达到什么目的? test.php 的内容存储在 $test 中吗?
我试过了:
$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(),只是file_get_contents()以字符串的形式返回文件。
【讨论】:
解决方案 #1: 使用 include(像函数一样工作):[我的最佳解决方案]
文件索引.php:
<?php
$bar = 'BAR';
$php_file = include 'included.php';
print $php_file;
?>
文件包含.php:
<?php
$foo = 'FOO';
return $foo.' '.$bar;
?>
<p>test HTML</p>
这将输出FOO BAR,但是
注意:像函数一样工作,所以 RETURN 将内容传递回变量(<p>test HTML</p> 将在上面丢失)
解决方案 #2: op_buffer():
文件索引.php:
<?php
$bar = 'BAR';
ob_start();
include 'included.php';
$test_file = ob_get_clean(); //note on ob_get_contents below
print $test_file;
?>
文件包含.php:
<?php
$foo = 'FOO';
print $foo.' '.$bar;
?>
<p>test HTML</p>
如果您使用ob_get_contents(),它将输出FOO BAR<p>test HTML</p> TWICE,请确保您使用ob_get_clean()
解决方案 #3: file_get_contents():
文件索引.php:
<?php
$bar = 'BAR';
$test_file = eval(file_get_contents('included.php'));
print $test_file;
?>
文件包含.php:
$foo = 'FOO';
print $foo.' '.$bar;
这将输出FOO BAR,但注意:Include.php 不应有<?php 开始和结束标记,因为您通过eval() 运行它
【讨论】:
ob_get_contents() 应该是 ob_get_clean() 否则它会输出两次。答案正在相应地编辑。
'included.php')进行硬编码? 3.如果传递给eval的参数包含html和嵌入式php标签的混合,会抛出错误吗?
<?php ?>。
eval 不允许混合使用 php 和 html。并且,回答我自己的问题 #2:是的,可以在 include 之后使用变量来动态给出文件名。
由于我不知道的原因,其他答案并没有完全达到正确的解决方案。
我建议使用缓冲区,但是你必须在页面结束之前获取内容然后清理缓冲区,否则它会被输出。如果您希望使用包含文件的输出,您应该使用op_get_contents(),它将返回缓冲区内容的字符串。
您也不需要遍历包含,因为每个只会添加到缓冲区中(除非您先清理它)。
因此您可以使用以下内容;
ob_start();
include_once('test.php');
include_once('test2.php');
$contents = ob_get_contents();
ob_end_clean();
希望这会有所帮助。
【讨论】:
您可以使用函数file_get_contents。
【讨论】: