使用file_get_contents()在html文件中设置php变量

B L*_*B L 1 html php phpmailer

我有一个自动电子邮件系统设置为发送html文件作为电子邮件.我使用PHPMailer将该文件带入我的电子邮件中

$mail->msgHTML(file_get_contents('mailContent.html'), dirname(__FILE__));
Run Code Online (Sandbox Code Playgroud)

在PHP源代码中,在我添加mailContent.html之前,我有一个变量$name='John Appleseed'(它是动态的,这只是一个例子)

在HTML文件中,我想知道是否有一种方法可以$name<p>标记中使用此变量.

A.L*_*A.L 7

您可以%name%mailContent.html文件中添加特殊字符串,然后可以使用您想要的值替换此字符串:

mailContent.html:

Hello %name%,
…
Run Code Online (Sandbox Code Playgroud)

在您的PHP代码中:

$name='John Appleseed';

$content = str_replace('%name%', $name, file_get_contents('mailContent.html'));
Run Code Online (Sandbox Code Playgroud)

$content会有价值Hello %name%, …,你可以发送:

$mail->msgHTML($content, dirname(__FILE__));
Run Code Online (Sandbox Code Playgroud)

您还可以str_replace()使用两个数组在一次调用中替换多个字符串:

$content = str_replace(
    array('%name%', '%foo%'),
    array($name,    $foo),
    file_get_contents('mailContent.html')
);
Run Code Online (Sandbox Code Playgroud)