如何在PHP中将文件的内容分配给变量

H. *_*nce 10 php include

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

我有这行代码:

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

当我做的时候,var_dump()我得到了string(1) "'"

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

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

谢谢.

lon*_*day 23

如果有需要执行的PHP代码,确实需要使用include.但是,include不会从文件返回输出; 它将被发送到浏览器.您需要使用名为output buffering的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
Run Code Online (Sandbox Code Playgroud)


Tim*_*per 13

你应该使用file_get_contents():

$body1 = file_get_contents('email_template.php');
Run Code Online (Sandbox Code Playgroud)

include包含并执行email_template.php当前文件,并存储include()to 的返回值$body1.

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

ob_start();
include 'email_template.php';
$body1 = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)