1

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

1
  • That would be because you haven't told it to do anything with $htmlInvoice, such as string replacement. Commented May 12, 2019 at 15:07

3 Answers 3

3

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

<?php

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

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

Strtr

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

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

Then

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

$msg = _readphp_eval($htmlInvoice);

function _readphp_eval($code) {
  ob_start();
  print eval('?>'. $code);
  $output = ob_get_contents();
  ob_end_clean();
  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.

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.