I have an email template that is inside a PHP script. I am using PHPmailer and the message that is sent is stored in a variable called $msg.
How can I set $msg to be the email template include file? I’m hoping there is a way to do this dynamically with an include file so that I don’t have to store 20 copies of the template in different scripts.
You have multiple approaches, three of which I will mention below.
Solution no. 1 – simple inclusion
First of all, if you include a file like in the following example:
its code will be executed exactly as if it was pasted instead of the above mentioned line. Thus if you will add value declaration in
myfile.php, the variable will be available just afterinclude()function call (mentioned above).So, basically, you can do something like that in
myfile.phpfile:and use
$msgvariable anywhere afterinclude()call in the main file (unless the variable has been overwritten).Solution no. 2 – inclusion with use of
returnFor use in some cases, eg. when you only include files containing some values you want to use (the main purpose of the file is to give some value to be processed), you may wish to use the following example. It should not interfere with your current variables (if used correctly).
In the main file:
and in the
myfile.phpfile:This way your file works only by returning specific variable and does not break the naming convention from your other files. Also you are free to call the variable the way you like without the need to change the configuration file’s content.
Solution no. 3 – output buffering
In some cases (messy coding, HTML etc.) you may be required to use this solution. The following code catches everything emitted by the file and saves it into variable
$msg, then turns the buffering off.This way, if you have eg.
echocalls, or some static HTML, within the included file, it will not be written “as is” and could be processed further (eg. some tokens from your template may be replaced with the actual data you want to use).So, basically, in this case you can even write in
myfile.phpsomething like:or even:
(just a text, not PHP code).