Php html email using html template

so I'm trying to make sytem html mail and my html, I want to be a template stored in a separate file, for example:

<div clas="headr"></div>
    <div class="content"></div>
<div class="footer"></div>

when I want to send mail, I want my mail content (from the input form) to go to this div.content and then send all the html (template + sent text). What is the best way to do this? I think something like:

  • import a template into my php that sends mail
  • find the div with the "content" class and add the text presented to it.
  • send mail

but I don’t know how to β€œfind” this div and write the submitted text into it.

+3
source share
5 answers

, str_replace . :

<div clas="header"></div>
<div class="content">{{content}}</div>
<div class="footer"></div>

:

$content = 'Whatever you want to insert...';
$tpl = file_get_contents('yourtemplate.html');
$tpl = str_replace('{{content}}', $content, $tpl);
mail($tpl, ...);
+16

PHP script , PHP , :

template.html:

<div clas="headr"></div>
    <div class="content"><?php echo $body; ?></div>
<div class="footer"></div>

, , PHP-:

$body = "Put this into the content tag...";
ob_start();
include("template.html");
$email = ob_get_clean();

: , , , , , . :.

<table>
 <tr>
  <td>Name:</td>
  <td><?php echo $name; ?></td>
 </tr>
 <tr>
  <td>Email:</td>
  <td><?php echo $email; ?></td>
 </tr>
</table>

, , html .

+17
+2

, Programmers.StackExchange, PHP .

PHP :

+1

If you want to avoid using placeholders or PHP code inside your template, you can look at phpQuery , which is the PHP Port for jQuery.

In your example, you would look like this (see docs ):

<?php
$body = 'The body of your email message';

$template = file_get_contents('template.html');
$email = pq('div.content').html($body);
?>

It may seem a little redundant, but if you intend to add more of the same features based on the CSS selector, just want to get the dirty hands of designers from PHP, this might be a good solution.

0
source

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


All Articles