如何在PHP中将文件的内容分配给变量 [英] How to assign the contents of a file to a variable in PHP

查看:70
本文介绍了如何在PHP中将文件的内容分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a document file containing HTML markup. I want to assign the contents of the entire file to a PHP variable.

我有这行代码:

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

当我做 var_dump()我得到字符串(1)'

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

Is it possible to assign the contents of a file to a variable?

[注意:这样做的原因是我要将邮件的主体段与邮件程序脚本 - 有点像模板,因此用户只需修改HTML标记,而无需关注我的邮件程序脚本。所以我将文件包含在邮件($ to,$ subject,$ body,$ headers,$ return_path)的整个主体段中;

[Note: the reason for doing this is that I want to separate the body segment of a mail message from the mailer script -- sort of like a template so the user just modifies the HTML markup and does not need to be concerned with my mailer script. So I am including the file as the entire body segment on mail($to, $subject, $body, $headers, $return_path);

谢谢。

推荐答案

如果有需要执行的PHP代码,确实需要使用 include 。但是, include 不会返回文件的输出;它将被发送到浏览器。您需要使用名为output buffering的PHP功能:它捕获脚本发送的所有输出。然后,您可以访问和使用此数据:

If there is PHP code that needs to be executed, you do indeed need to use include. However, include will not return the output from the file; it will be emitted to the browser. You need to use a PHP feature called output buffering: this captures all the output sent by a script. You can then access and use this data:

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

这篇关于如何在PHP中将文件的内容分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆