B L B L - 5 months ago 84x
PHP Question

Setting php variable in html file using file_get_contents()

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
variable in a


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),