B L B L - 7 months ago 131
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
$name
variable in a
<p>
tag.

A.L A.L
Answer

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')
);
Comments