Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read HTML file into email

Tags:

html

php

email

Ive written a script to send html emails and all works well. I have the email stored in a separate HTML file which is then read in usin a while loop and fgets(). However, i want to be able to pass variables into the html. For example, in a html file i may have something like..

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

and i read this into a string like so

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

I want to be able to replace "Name" in the html file by a variable and im not entirely sure on the best way to do this. I could always make my own tag and then use regex to replace that with the name once ive read the file into the string, but im wondering if there is a better/easier method to do this.

(On a side note, if anyone knows whether its better to use file_get_contents instead of multiple calls to fgets, id be interested to know)

like image 454
cast01 Avatar asked Aug 28 '26 07:08

cast01


2 Answers

str_replace() also has the disadvantages of potentially matching and replacing things that you might not want to. Smarty is definitely overkill for this, I would follow Matt's suggestion above by doing something like the following

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

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

email.html.php would look like this

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

and you can call it like this

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

You'll never match anything by mistake this way and it's easily extended with other variables etc. without having to use addition str_replace() calls.

If you need to go much further than that, it might be worthwhile looking at Smarty.

like image 152
El Yobo Avatar answered Aug 30 '26 23:08

El Yobo


You could use str_replace() to define placeholders like

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

and then replace them on the fly:

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

Using file_get_contents() or fopen() is both all right.

like image 25
Pekka Avatar answered Aug 30 '26 22:08

Pekka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!