Home > Blockchain >  How to replace email template placeholder with an array in php
How to replace email template placeholder with an array in php

Time:03-27

I am trying to send the user an email with the chosen programs. I have an email template where I set placeholders for the data to be replaced. The problem is that I have a placeholder I want to replace with an array, but only the first element that is being displayed.

this is the part of the email template to be replaced with an array

`<p style="margin: 0; font-size: 14px; text-align: left; mso-line-height-alt: 21.6px;"><span 
 style="font-size:12px;">Programs: {{progName-placeholder}}</span></p>` 

and in my sendEmail() function

`$Body = file_get_contents('template.php');
 foreach($_SESSION['courseName'] as $course){
    $Body = str_replace('{{progName-placeholder}}',$course , $Body);
  }`

I have also tried this, but it sends me each program in a separate email body.

`$elements = array();
 foreach($_SESSION['courseName'] as $course){
    $elements[] = str_replace('{{progName-placeholder}}',$course, $Body);      
      }
  $Body= implode(',', $elements);` 

any help is appreciated

CodePudding user response:

I'd suggest to simply implode the array. This will generate a string that you can replace within your template.

The first argument of implode is the character separator which will be added to join the elements of the array.

$courses = implode(', ', $_SESSION['courseName']);
$Body = file_get_contents('template.php');
$Body = str_replace('{{progName-placeholder}}', $courses, $Body);

CodePudding user response:

$_SESSION['courseName'] = ['IOT', 'Web dev', 'UI/UX'];
// $Body = file_get_contents('template.php');
$Body =  '<p style="margin: 0; font-size: 14px; text-align: left; mso-line-height-alt: 21.6px;"><span style="font-size:12px;">Programs: {{progName-placeholder}} </span></p>
';

$templated_courses = "";

foreach ($_SESSION['courseName'] as $course) {
    $templated_courses .= str_replace('{{progName-placeholder}}', $course, $Body);
}

// Send $templated_courses
echo $templated_courses;

Demo

  • Related