I have an automated email system set up to send an html file as an email. I bring that file into my email with PHPMailer, using
$mail->msgHTML(file_get_contents('mailContent.html'), dirname(__FILE__));
In the PHP source, before I add the mailContent.html, I have a variable $name='John Appleseed' (it is dynamic, this is just an example)
In the HTML file, I'm wondering if there is a way that I can use this $name variable in a <p> tag.
You can add a special string like %name% in your mailContent.html file, then you can replace this string with the value your want:
In mailContent.html:
Hello %name%,
…
In your PHP code:
$name='John Appleseed';
$content = str_replace('%name%', $name, file_get_contents('mailContent.html'));
$content will have the value Hello %name%, …, you can send it:
$mail->msgHTML($content, dirname(__FILE__));
You can also replace several strings in one call to str_replace() by using two arrays:
$content = str_replace(
array('%name%', '%foo%'),
array($name, $foo),
file_get_contents('mailContent.html')
);
And you can also replace several strings in one call to strtr() by using one array:
$content = strtr(
file_get_contents('mailContent.html'),
array(
'%name%' => $name,
'%foo%' => $foo,
)
);
You need to use a templating system for this. Templating can be done with PHP itself by writing your HTML in a .php file like this:
<html>
<body>
<p>
Hi <?= $name ?>,
</p>
<p>
This is an email message. <?= $someVariable ?>
</p>
</body>
</html>
Variables are added using <?= $variable ?> or <?php echo $variable ?>. Make sure your variables are properly escaped HTML using htmlspecialchars() if they come from user input.
And then to the template in your program, do something like this:
$name = 'John Appleseed';
$someVariable = 'Foo Bar';
ob_start();
include('template.php');
$message = ob_get_contents();
ob_end_clean();
$mail->msgHTML($message, dirname(__FILE__));
As well as using PHP for simple templating, you can use templating languages for PHP such as Twig.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With