OrangeTwine
OrangeTwine

Reputation: 45

Can't pass a PHP variable to file_get_contents()

I am a newbie coder trying to build a simple web app using PHP. I am trying to send an HTML email that has a variable that will change each time it is sent. The code to initiate the email is 'email.php' and contains:

$body = file_get_contents('welcome/green2.html.php');

Within the 'green2.html.php' file, I have a variable called $highlight that needs to be populated. The $highlight variable is defined within the 'email.php' file. I had tried to simply add within the 'green2.html.php' file, however it is not being parsed. I get a blank space where the variable should be when it is output.

Also, I have done an include 'welcome/green2.html.php' within the 'email.php' file. When I echo it, the $highlight var is shown on the resulting page, but not if I echo $body.

Any help would be much appreciated!

Upvotes: 1

Views: 1694

Answers (3)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5186

Use http://php.net/manual/en/function.sprintf.php put a %s in your code instead of the variable read the content and put the string into the sprintf with the variable you want to put that's it. Hope this will help.

Upvotes: 0

Spudley
Spudley

Reputation: 168843

Loading a file via file_get_contents() will not cause it to be parsed by PHP. It will simply be loaded as a static file, regardless of whether it contains PHP code or not.

If you want it to be parsed by PHP, you would need to include or require it.

But it sounds like you're trying to write a templating system for your emails. If this is what you're doing, you'd be better off not having it as PHP code to be parsed, but rather having placeholder markers in it, and then using str_replace() or similar functions to inject variables from your main program into the string.

Hope that helps.

Upvotes: 1

Dan
Dan

Reputation: 526

Have you tried the str_replace function? http://php.net/manual/en/function.str-replace.php.

Add a placeholder in HTML (for instance #name# for name, #email# for email), and then use the string replace function once you've loaded the content of the file.

$bodytag = str_replace("#name#", $name, $myfile);

Upvotes: 5

Related Questions