且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-11 18:11:26

如果有需要执行的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