I have a PHP code which sends an email with HTML template. HTML template has some PHP variable like Name, Email, etc.

<strong>Name: {name} </strong>

because email template has more code, I include it in my PHP file

$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');

$name= $user['name']);

$msg = $htmlInvoice;

But when an email sent, it can not read variables inside the HTML file. and for example echo $name like a text

3 Answers

Abhishek On Best Solutions

You can use strtr for this. For e.g:


$a = 'Hi this is {name}. I am writing {language}';

echo strtr($a, ['{name}' => 'Abhishek', '{language}' => 'php']);


Carlos Alves Jorge On

You need to replace the {name} string for your desired output.

$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');

$name= $user['name']);

$msg = str_replace('{name}',$name, $htmlInvoice);
Wayne On

You could change /mail/invoice.html to include PHP commands.

<strong><? echo $user['name'] ?></strong>


$htmlInvoice = file_get_contents($_SERVER["DOCUMENT_ROOT"] .'/mail/invoice.html');

$msg = _readphp_eval($htmlInvoice);

function _readphp_eval($code) {
  print eval('?>'. $code);
  $output = ob_get_contents();
  return $output;

I don't know who to attribute _readphp_eval($code) function to ... It is floating around the internet, and works very nicely for this purpose.

It would require that $user['name'] be defined/included in the invoice.html file.