如何使用PhpMailer将多个变量传递给html模板?

时间:2016-02-17 09:18:26

标签: php html email phpmailer

我想将多个变量传递给Mail模板页面并使用phpmailer库回显到该页面。

我有两个变量来传递welcome.php页面并在那里回显。

$name = 'example';
$email = 'example@mail.com';

我已经使用了这段代码

 $mail->MsgHTML(str_replace('[emailhere]', $email, file_get_contents('welcome.php')), dirname(__FILE__));

2 个答案:

答案 0 :(得分:2)

您可以将数组发送到str_replace以替换多个值。

例如:

$message = str_replace(
    array(
      '[emailhere]',
      '[namehere]'
    ),
    array(
       $email,
       $name
    ),
    file_get_contents('welcome.php')
);

顺便说一句,您可能不应该为您的模板提供php扩展名,因为如果您直接调用或包含它,它将解析任何php。因此,如果用户可以修改模板,那么这可能会带来安全风险。

答案 1 :(得分:0)

您可以使用输出缓冲。

模板文件上的回显变量($ template): 例如:

<p><?=$name?></p>

然后包含它并通过输出缓冲

ob_start(); //Start output buffering
include('welcome.php'); //include your template file
$template = ob_get_clean(); //Get current buffer contents and delete current output buffer
$mail->msgHTML($template); // Add html content into your PHP MAILER class