如何将PHP include定义为字符串?

23

我尝试了:

$test = include 'test.php';

但那只是正常地包含了文件


4
你能说得更详细一些吗?(意思是希望对方提供更多的细节或信息) - The Pixel Developer
1
你想要实现什么?是将test.php的内容存储在$test中吗? - Boldewyn
6个回答

35

你需要查看输出缓冲函数。

//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');

这应该等同于我更冗长的原始解决方案。

但我并没有费心测试这个。


2
为什么需要停止任何现有的缓冲区?PHP 中的输出缓冲区栈:http://php.net/ob_start - Jeremy Kauffman
2
这不是问题,我只是没有注意到可堆叠性。正在编辑我的答案。 - timdev

11

试试这样做:

ob_start();
include('test.php');
$content = ob_get_clean();

8
尝试使用 file_get_contents() 函数。

该函数与 file() 类似,但是 file_get_contents() 返回文件的字符串。


绝对是这里最好的答案。简短而聪明。 - Fancy John

5

解决方案 #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()运行它。

1
如果缓冲区在文件结束之前没有被保留和清理,那么缓冲区输出两次的唯一原因是缓冲区被自动回显。也许这就是你一直遇到的问题。 - worldofjr
1
啊,谢谢@worldofjr,虽然你没有具体说明但是指引了我正确的方向;ob_get_contents()应该改为ob_get_clean(),否则会输出两次。答案正在相应地进行编辑。 - Duncanmoo
  1. 解决方案#3更好吗?
  2. 在解决方案#2中,您可以使用一个变量来表示文件名,还是必须硬编码文件名(例如'included.php')?
  3. 如果传递给eval的参数包含HTML和嵌入式PHP标记,会抛出错误吗?
- toddmo
@toddmo 我认为选项#3是最糟糕的,我不想在我的Web根目录中放置文件,然后直接通过浏览器调用以呈现实际的PHP代码文本。在我看来,所有的PHP都应该被<?php ?>包围。 - Duncanmoo
@Duncanmoo,我必须选择第二个选项。eval不允许混合使用php和html。另外,回答一下我的问题#2:是的,可以在include之后使用变量,以动态地给出文件名。 - toddmo

0

其他的答案,原因我不知道,都没有达到正确的解决方案。

我建议使用缓冲区,但是你必须在页面结束之前获取内容并清空缓冲区,否则会输出。如果你想使用包含文件的输出,你应该使用op_get_contents(),它会返回缓冲区内容的字符串。

你也不需要循环遍历包含文件,因为每个文件只会添加到缓冲区(除非你先清空它)。

因此,你可以使用以下代码:

ob_start();
include_once('test.php');
include_once('test2.php');
$contents = ob_get_contents();
ob_end_clean();

希望这能有所帮助。

-1

1
我想知道为什么你们会建议使用输出缓冲,当这种方法明显更简单。 - Ruan Mendes
17
也许是因为file_get_contents函数不会执行文件中的PHP代码? - fool4jesus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接