Reading HTML file to email

Ive written a script to send html emails and everything works fine. I have an email stored in a separate HTML file, which is then read in a while and fgets () loop. However, I want to be able to pass variables to html. For example, in an html file I might have something like.

<body>
    Dear Name <br/>
    Thank you for your recent purhcase
</body>

and I read it in a line like this

$file = fopen($filename, "r");
while(!feof($file)) {
    $html.= fgets($file, 4096);
}
fclose ($file);

I want to be able to replace the "Name" in the html file with a variable, and I'm not quite sure if this is the best way to do this. I could always make my own tag and then use the regex to replace it with the name as soon as I read the file in a line, but they are wondering if there is a better / easier way to do this.

( , - , file_get_contents fgets, id )

+3
5

str_replace() , , , . Smarty , , -

function getEmailContents(array $vars) {
  extract($vars);

  ob_start();
  include 'email.html.php';
  return ob_get_clean();
}

email.html.php :

<body>
    Dear <?php echo $name; ?> <br/>
    Thank you for your recent purhcase of <?php echo $product; ?>
</body>

$emailContents = getEmailContents(array('name' => 'El Yobo', 'product' => 'Something'));

- , .., str_replace().

, , Smarty.

+4

str_replace() ,

Dear %name
Thank you for your recent purchase of %product

:

$html = str_replace("%name", $order_name, $html);
$product = str_replace("%product", $order_product, $html);

file_get_contents() fopen() - .

+3

PHP include. fgets replace .

ob_start();
include("yourTemplate.html.php");

$html = ob_get_clean();

// $html now has whatever your template output
+2

, , Smarty, . , PHP str_replace() - , , , , strtr() ( ).

+1
source

You might want to use the template system if you expect any additional features in the future.

0
source

Source: https://habr.com/ru/post/1739985/


All Articles