Andre Bulatov Andre Bulatov - 4 months ago 16
PHP Question

Provided that I want to keep the HTML in a separate file, how can I pass PHP variables to the HTML before sending it out?

How do I pass a PHP variable to an HTML file (to be used as an email template) included with

file_get_contents
?


  1. First I set some variables:

    $variable = 'Hello or else!';

  2. I get the HTML/PHP email template like this:

    $html_email_body = file_get_contents('/var/www/folder/email.php');

  3. In that PHP/HTML email file, I am using the pre-defined variables like this:

    <p><?php echo $variable; ?></p>

  4. Then finally sending it out with PHPMailer.

    $mail->Body = $email_body;
    PHPMailerFunc( $html_email_body );



The mailing works perfectly, but the HTML email content is blank where the
$variable
string should be.

Provided that I want to keep the HTML in a separate file, how can I pass PHP variables to the HTML before sending it out?

PS: I know
file_get_contents
retrieves content and parses it into a string, so what I am doing can't really work. Is there maybe some way to
include
the HTML?

My code in the HTML template

<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Email Title</title>
<style>
* {
font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
...
</tr>
</table>
<p face="arial, sans, sans-serif"><?php echo $variable['key']; ?></p>
<p face="arial, sans, sans-serif"><?php echo $variable['key2']; ?></p>
</body>
</html>


*I have tried doing
var_dump($variable)
and it contains the right stuff.

Answer

NO. but here is the must popular way around it.

$rpl = array(
              '$variabe' => 'Hello or else!'
            );

$e_tpl = file_get_contents('/var/www/folder/email.php');
$mail = str_replace(array_keys($rpl), array_values($rpl), $e_tpl);
$mail->Body = $email;

Then you can use <p> $variable </p> in email.php

Comments