user3369276
user3369276

Reputation: 71

Parsing values in php

so I have a table in which I have email templates, and these email templates can be later fetched for sending emails.

The structure is :-

for_status     subject          message
 int             text           text

An example entry is :-

for_status = 1,
subject = Transaction Status Changed,
message = Hi $user->firstname, this is a test message.

Ok, so the problem is, when I send the email with the current message and subject, it displays in the email Hi $user->firstname, this is a test message

Instead of showing, Hi thefirstname here, this is a test message.

I'm fetching user details successfully on the same page in the $user variable. What's going wrong here?

Upvotes: 0

Views: 62

Answers (3)

Dave Morrissey
Dave Morrissey

Reputation: 4411

PHP will only perform the substitution for you on strings you have coded into your own PHP files, not those that have come from a database or any other source. If it did, that would be a massive security risk!

You will need to perform substitution on your template yourself.

// $message is: Hi %{userFirstName}, this is a test message.
$message = str_replace('%{userFirstName}', $user->firstname, $message);

Upvotes: 0

GGio
GGio

Reputation: 7653

You need something whats called placeholders. You need to decide what to have as a place holder, I personally use the following:

{%first_name%}, this is a test message.

Then in your PHP code you just have an array of placeholders & values like this:

$arr = array(
   '{%first_name%}' => $user->firstname,
);

//and now replace the body
$body = str_replace(array_keys($arr), $arr, $body);

There is a better way of doing this by using already written libraries or using Regular Expression to correctly parse, but I will leave that up to you to figure it out.

Upvotes: 1

mmundiff
mmundiff

Reputation: 3951

When you say "table of email templates", is the actual text of the email template in some sort of database?

If this is the case and you have $user->firstname in the database, I'm pretty sure its going to spit that out directly.

Upvotes: 1

Related Questions