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.

James
  • 5,137
  • 5
  • 40
  • 80
B L
  • 198
  • 3
  • 12
  • 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. – Marc B Apr 29 '16 at 18:04
  • http://stackoverflow.com/questions/14466090/php-replace-string-after-using-file-get-contents – VikingBlooded Apr 29 '16 at 18:05
  • Possible duplicate of [PHP replace string after using file\_get\_contents](http://stackoverflow.com/questions/14466090/php-replace-string-after-using-file-get-contents) – A.L Jan 08 '17 at 18:21

5 Answers5

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,
    )
);
A.L
  • 10,259
  • 10
  • 67
  • 98
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.

Candy Gumdrop
  • 2,745
  • 1
  • 14
  • 16
  • 1
    +1 for using a templating language - [Smarty](http://www.smarty.net) is old but still much more flexible than Twig, also faster and uses less memory! – Synchro Apr 30 '16 at 07:44
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');
Ryan
  • 14,392
  • 8
  • 62
  • 102
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;
}
James
  • 5,137
  • 5
  • 40
  • 80
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.

Erik Terwan
  • 2,710
  • 19
  • 28