如何在PHP中将文件内容赋值给变量

13

我有一个包含HTML标记的文档文件。我想将整个文件的内容分配给一个PHP变量。

我有以下代码:

$body = include('email_template.php');

当我使用var_dump()时,我得到了string(1) "'"

是否可以将文件的内容分配给一个变量?

[注意:这样做的原因是我想将邮件消息的正文部分与发件人脚本分离--有点像模板,因此用户只需修改HTML标记而不需要关心我的发件人脚本。所以我将文件包含为mail($to, $subject, $body, $headers, $return_path);的整个正文段。

谢谢。


在所包含的文件中,是否有任何PHP操作,还是只有纯文本? - lonesomeday
是的 @lonesomeday ... 我在问题中没有提到的一些事情是,我的 email_template.php 文件包含嵌入式 php。所以我想我需要 include() 它而不是 file_get_contents() 它。这是真的吗?get_file-contents() 仍然会解析为 php 吗? - H. Ferrence
7个回答

25

如果需要执行 PHP 代码,确实需要使用 include。然而,include 不会返回文件的输出结果,它会直接输出到浏览器。你需要使用 PHP 的输出缓冲功能:它可以捕获脚本发送的所有输出。然后你可以访问和使用这些数据:

ob_start();                      // start capturing output
include('email_template.php');   // execute the file
$content = ob_get_contents();    // get the contents from the buffer
ob_end_clean();                  // stop buffering and discard contents

1
ob_get_clean()ob_end_flush() 有什么区别?在我的情况下,哪一个最好使用? - H. Ferrence
@Dr.DOT ob_get_clean 返回内容。ob_end_flush 停止缓冲并将输出发送到浏览器,并返回布尔值。在这里,你不需要使用 ob_end_flush - lonesomeday
测试过了,完美运行。谢谢@lonesomeday——我今天学到了很酷的东西! - H. Ferrence
1
或者更短: ob_start(); include('email_template.php'); $content = ob_get_clean(); - Tigran

14

你应该使用file_get_contents()函数:

$body1 = file_get_contents('email_template.php');

include表示将email_template.php文件包含并在当前文件中执行,并将include()的返回值存储到$body1变量中。

如果你需要在文件中执行PHP代码,你可以使用输出控制:

ob_start();
include 'email_template.php';
$body1 = ob_get_clean();

1
感谢@TimCooper。我在问题中没有提到的是,我的email_template.php文件包含嵌入的php。所以我想我需要使用include()而不是file_get_contents()。这是真的吗?file_get_contents()仍然会解析为php吗? - H. Ferrence

3

file_get_contents()

$file = file_get_contents('email_template.php');

或者,如果你是疯狂的:

ob_start();
include('email_template.php');
$file = ob_end_flush();

1

正如其他人所发表的,如果该文件不需要以任何方式执行,则使用file_get_contents

或者,您可以使用return语句返回输出结果。

如果您的include文件需要处理并使用echo [ed:或离开PHP解析模式]语句输出,您也可以缓冲输出。

ob_start();
include('email_template.php');
$body1 = ob_get_clean();

TimCooper比我先发了。:P


0

可以的,很容易。

在你想要使用变量的文件中,加入以下内容:

require_once ‘/myfile.php';
if(isset($responseBody)) {
    echo $responseBody;
    unset($responseBody);
}    

在你调用的文件/myfile.php中加入以下内容:
$responseBody = 'Hello world, I am a genius';

谢谢 丹尼尔


从技术上讲,诀窍是在 require_once 文件之前定义变量名称,然后如果需要的话可以取消设置变量,以防止它覆盖脚本的其他部分,或者您可以像任何其他变量一样保留它。 - centralhubb.com

0

你有两个可选的选择

[选择1]

  1. 创建一个名为'email_template.php'的文件
  2. 在文件中添加一个变量,如下所示

    $body = '<html>电子邮件内容</html>';

  3. 在另一个文件中require_once 'email_template.php'

  4. 然后echo $body;

[选择2]

$body = require_once 'email_template.php';

0

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