如果我想将HTML保存在一个单独的文件中,那么如何在发送之前将PHP变量传递给HTML


Provided that I want to keep the HTML in a separate file, how can I pass PHP variables to the HTML before sending it out?

如何将PHP变量传递给file_get_contents中包含的HTML文件(用作电子邮件模板)?

  1. 首先我设置了一些变量:

    $variable = 'Hello or else!';
    
  2. 我得到的HTML/PHP电子邮件模板如下:

    $html_email_body = file_get_contents('/var/www/folder/email.php');
    
  3. 在那个PHP/HTML电子邮件文件中,我使用的预定义变量如下:

    <p><?php echo $variable; ?></p>
    
  4. 然后最后用PHPMailer发送出去。

    $mail->Body    = $email_body;
    PHPMailerFunc( $html_email_body );
    

邮件工作正常,但HTML电子邮件内容在$variable字符串应该所在的位置是空白的。

如果我想将HTML保存在一个单独的文件中,我如何在发送HTML之前将PHP变量传递给它?

PS:我知道file_get_contents检索内容并将其解析为字符串,所以我所做的并不能真正起作用。是否有某种方法可以include HTML?

HTML模板中的我的代码

<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Email Title</title>
<style>
* {
  font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
...
  </tr>
</table>
<p face="arial, sans, sans-serif"><?php echo $variable['key']; ?></p>
<p face="arial, sans, sans-serif"><?php echo $variable['key2']; ?></p>
</body>
</html>

*我试过做var_dump($variable),它包含了正确的内容。

NO。但这是一个必须流行的方法。

$rpl = array(
              '$variabe' => 'Hello or else!'
            );
$e_tpl = file_get_contents('/var/www/folder/email.php');
$mail = str_replace(array_keys($rpl), array_values($rpl), $e_tpl);
$mail->Body = $email;

然后您可以在email.php 中使用<p> $variable </p>

我认为这是模板引擎的工作,但不用担心,它非常容易使用。

你只需要用composer准备项目,然后轻松安装一个模板引擎(对于这个例子,我选择了Latté)。

作曲家安装:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php

之后安装Latté:

php composer.phar require latte/latte

最后,你可以创建这样的东西:

$latte = new 'Latte'Engine;
$latte->setTempDirectory('/path/to/tempdir');
$parameters['variable'] = 'Hello or else';
$html = $latte->renderToString('email.latte', $parameters);

并将这些内容放入同一目录中的文件"email.ratte"中:

<p>{$variable}</p>

好的方面是-所有变量都是自动转义的(以避免XSS)。因此,如果你只使用纯HTML,你会更安全。

这个问题主要是基于观点的。。不过,在我看来,应该使用输出缓冲区,只使用include作为模板文件,然后将缓冲区的内容存储在$html_email_body变量中。

像这样:

// 1. Turn on output buffering
ob_start();
// 2. Set your variables here
$variable = 'Hello or else!';
// 3. Include your template file, all output will be stored in a buffer
include '/var/www/folder/email.php';
// 4. Call ob_get_clean() to get the contents of the buffer
$html_email_body = ob_get_clean();
// 5. Send the email
$mail->Body    = $email_body;
PHPMailerFunc( $html_email_body );