2

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.

3
  • not with file_get_contents. it just slurps in some bytes and returns those bytes as a string. If you were doing include(), then any php inside that html would get executed, but then it also wouldn't return the generated html as a string. Commented Apr 29, 2016 at 18:04
  • stackoverflow.com/questions/14466090/… Commented Apr 29, 2016 at 18:05
  • Possible duplicate of PHP replace string after using file_get_contents Commented Jan 8, 2017 at 18:21

5 Answers 5

11

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,
    )
);
Sign up to request clarification or add additional context in comments.

3 Comments

That's perfect! Thank you
not a very scalable solution, but that is a viable solution as well.
@self I added some code to perform several replacements in the same call to str_replace().
3

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.

1 Comment

+1 for using a templating language - Smarty is old but still much more flexible than Twig, also faster and uses less memory!
1

Here is a function to do it using extract, and ob_*

extract will turn keys into variables with their value of key in the array. Hope that makes sense. It will turn array keys into variables.

function getHTMLWithDynamicVars(array $arr, $file)
{
    ob_start();

    extract($arr);

    include($file);

    $realData = ob_get_contents();

    ob_end_clean();

    return $realData;
}

Caller example:

$htmlFile = getHTMLWithDynamicVars(['name' => $name], 'mailContent.html');

2 Comments

What should be written in the source HTML file? Will it replace name?
You can do <h1><?php echo $name; ?></h1> . Just use the source file as you would a html file with variables in PHP.
0

In one of my older scripts I have a function which parses a file for variables that look like {{ variableName }} and have them replaced from an array lookup.

function parseVars($emailFile, $vars) {
    $vSearch = preg_match_all('/{{.*?}}/', $emailFile, $vVariables);

    for ($i=0; $i < $vSearch; $i++) {
        $vVariables[0][$i] = str_replace(array('{{', '}}'), NULL, $vVariables[0][$i]);
    }

    if(count($vVariables[0]) == 0) {
        throw new TemplateException("There are no variables to replace.");
    }

    $formattedFile = '';
    foreach ($vVariables[0] as $value) {
        $formattedFile = str_replace('{{'.$value.'}}', $vars[$value], $formattedFile);
    }

    return $formattedFile;
}

Comments

0

Do you have the $name variable in the same file where you send the mail? Then you can just replace it with a placeholder;

Place __NAME__ in the HTML file where you want the name to show up, then use str_ireplace('__NAME__', $name, file_get_contents('mailContent.html')) to replace the placeholder with the $name variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.