我正在制作一个用于发送发票的邮件应用程序,我有一个HTML电子邮件发票模板。
<?php
include 'dbconfig.php';
$q = intval($_GET['q']);
$sql="SELECT * FROM clients WHERE id = '".$q."'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
$to = "name@example.com";
$subject = "Invoice Test " . date('m/d/Y h:i:s a', time());
$invoice = fopen("invoice.html", "r") or die("Unable to open invoice template file");
$message = fread($invoice, filesize("invoice.html"));
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: billing@example.com' . "\r\n";
$headers .= 'BCC: billing@example.com' . "\r\n";
mail($to,$subject,$message,$headers);
echo $message;
fclose ($invoice);
}
mysqli_close($conn);
?>
此代码可以完美运行,但是我想在模板文件中运行PHP代码,例如<? echo $row[id]; ?>
,以使用来自MySQL调用的数据来填充模板的空白。我怎样才能做到这一点? fopen不运行PHP代码。有点像require_once
,但我可以在此应用程序中使用它。
如果无法做到这一点,我将诉诸于在主文档中包含index-template.php,然后在$message = ' <html code> ';
处格式化该辅助文档-这只会使模板更新变得更加困难。>
答案 0 :(得分:1)
最简单的方法就是使用输出缓冲来捕获输出,然后包含文件而不是读取文件:
// start output buffering
ob_start();
// include your file, which parses the php in it
include 'invoice.html';
// close the output buffer and get its contents
$message = ob_get_clean();