phphtmlemailhtml-tablehtml-email

PHP foreach loop insert into PHP variable


I need some help constructing the proper structure for an HTML email that I am trying to send using PHP. Here is the line which sends the email:

$this->_send_user_email($recipient, $subject, $message);

Where I am having trouble is constructing the $message. I need the $message to include a table with a dynamic number of rows. Here is the current structure of the $message variable:

$message = "Hello, <br><br> 
Please review details in the table below:
<br><br>
**** NEED TO INSERT DYNAMIC PHP TABLE HERE ****
<br><br>
If you have questions, please call 1-888-888-8888 and we will assist you.
<br><br>
Customer Support<br> 
<br><br>
";  

I am unsure of how to insert my PHP foreach loop inside this existing $messsage variable. I get confused about when to close the quotes and how to continue etc. Here is the code for the foreach loop that I am trying to insert:

<?php if (is_array($foo['bar'])):  ?>    
<table>
    <tr>
        <th >1</th>
        <th >2</th>
        <th >3</th>
    </tr>
<?php $row = 01; 
foreach ($foo['bar'] as $key => $value): ?>
<tr>
    <td ><?php echo str_pad($row++, 2, '0', STR_PAD_LEFT); ?></td>
    <td >AAA</td>
    <td >BBB</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

So I guess my question is: What is the correct way to insert this PHP foreach loop into the $message variable above?


Solution

  • A way of doing this is splitting the template message in two strings say $message1 and $message2 where the first contains everything up until the dynamic table and the latter everything that starts after the table. Then you generate your dynamic table with string concatenation and you concatenate the three parts of the whole message.

    $message1 = "Hello, <br><br> 
    Please review details in the table below:
    <br><br>";
    
    $message2 = "<br><br>
    If you have questions, please call 1-888-888-8888 and we will assist you.
    <br><br>
    Customer Support<br> 
    <br><br>";
    
    $row = "01";
    
    $table = "";
    
    if(is_array($foo['bar'])) {   
    
        $table .= "<table>
                    <tr>
                        <th >1</th>
                        <th >2</th>
                        <th >3</th>
                    </tr>"; 
    
        foreach($foo['bar'] as $key => $value) {
            $table .= "<tr>
                         <td >" . str_pad($row++, 2, '0', STR_PAD_LEFT) . "</td>
                         <td >AAA</td>
                         <td >BBB</td>
                       </tr>";
        }
    
        $table .= "</table>";
    }
    
    $message = $message1 . $table. $message2;
    

    Now as someone mentioned in the comments, this code will work but is quite messy, in the sense that you heavily mix php logic and plain html text. Ideally you want to separate these two as much as possible.