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


how to pass multiple variable to html template Using PhpMailer?

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

我有两个变量要传递欢迎.php页面并在那里回显。

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

我使用了这个代码

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

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

例如:

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

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

您可以使用输出缓冲。

模板文件 ($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