您好我正在尝试使用php邮件程序类发送HTML电子邮件.问题是我想在我的电子邮件中包含php变量,同时使用包含以保持组织有序.继承人我的php邮件....
$place = $data['place'];
$start_time = $data['start_time'];
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "You have an event today";
$mail->Body = file_get_contents('../emails/event.html');
$mail->Send(); // send message
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否有可能在event.html中有php变量?我试了这个没有运气(下面是event.html)..
<table width='600px' cellpadding='0' cellspacing='0'>
<tr><td bgcolor='#eeeeee'><img src='logo.png' /></td></tr>
<tr><td bgcolor='#ffffff' bordercolor='#eeeeee'>
<div style='border:1px solid #eeeeee;font-family:Segoe UI,Tahoma,Verdana,Arial,sans-serif;padding:20px 10px;'>
<p style=''>This email is to remind you that you have an upcoming meeting at $place on $start_time.</p>
<p>Thanks</p>
</div>
</td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)
Nic*_*ole 21
是的,非常容易使用include和一个简短的帮助函数:
function get_include_contents($filename, $variablesToMakeLocal) {
extract($variablesToMakeLocal);
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "You have an event today";
$mail->Body = get_include_contents('../emails/event.php', $data); // HTML -> PHP!
$mail->Send(); // send message
Run Code Online (Sandbox Code Playgroud)
该get_include_contents
函数由PHP include
文档提供,稍作修改以包含一组变量.
重要提示:由于您的include是在函数内处理,因此PHP模板file(/emails/event.php
)的执行范围在该函数的范围内(除了超级全局变量外没有其他变量可用)
这就是我添加的原因extract($variablesToMakeLocal)
- 它从$variablesToMakeLocal
函数范围中的变量中提取所有数组键,这反过来意味着它们在包含的文件的范围内.
既然你已经拥有place
并且start_time
在$data
数组中,我只是直接将其传递给函数.您可能想知道这将提取其中的所有密钥$data
- 您可能想要也可能不想要.
请注意,现在您的模板文件正在作为PHP文件处理,因此所有相同的警告和语法规则都适用.你应该不将其暴露在被外界进行编辑,并且必须使用<?php echo $place ?>
输出变量,在任何PHP文件.
pro*_*son 11
几种方法:
令牌模板
<p> Some cool text %var1%,, %var2%,etc...</p>
Run Code Online (Sandbox Code Playgroud)
令牌邮件程序
$mail->Body = strtr(file_get_contents('path/to/template.html'), array('%var1%' => 'Value 1', '%var2%' => 'Value 2'));
Run Code Online (Sandbox Code Playgroud)
缓冲模板
<p> Some cool text $var1,, $var2,etc...</p>
Run Code Online (Sandbox Code Playgroud)
缓冲梅勒
$var1 = 'Value 1';
$var2 = 'Value 2';
ob_start();
include('path/to/template.php');
$content = ob_get_clean();
$mail->Body = $content;
Run Code Online (Sandbox Code Playgroud)