Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
B L Avatar asked Jan 30 '26 21:01

B L


2 Answers

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,
    )
);
like image 167
A.L Avatar answered Feb 02 '26 10:02

A.L


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:

template.php:

<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.

like image 35
Candy Gumdrop Avatar answered Feb 02 '26 10:02

Candy Gumdrop