PHP使用HTML模板

I am having trouble reading in a file and using it as a template in PHP. A portion of my code is pasted below. For some reason it never finds $$USER_NAME$$ in the string so it never replaces. I also pasted the beginning part of my template below.

$filename = "email/templates/welcome.txt";
$file = fopen($filename, "r")   
$body = fread($file, filesize($filename));
fclose($file);
$body = str_replace("$$USER_NAME$$", "John Doe", $body);
print($body);

Template:

<p>
   <img src="emailPic" alt="Logo" />
</p>
<p>Dear $$USER_NAME$$,</p>
<p>Thank you for registering to attend $$EVENT_NAME$$. We look forward to helping you reach your networking goals at $$EVENT_SHORT_NAME$$.
</p>...

Any ideas about why it wouldn't find $$USER_NAME$$ in the template?

Try with single quotes:

$body = str_replace('$$USER_NAME$$', 'John Doe', $body);

otherwise the $ signs get interpreted by PHP (just try to do echo "$$USER_NAME$$" to understand that PHP will interpret it as echo $$USER_NAME."$$" or something similar).

You can as well resolve the problem by escaping the $ if you still want to use double quotes:

$body = str_replace("\$\$USER_NAME\$\$", "John Doe", $body);

Check the PHP manual page on Strings to know what are the differences between single quoted and double quoted strings in PHP.

Your string "$$USER_NAME$$" needs to escape the dollar signs: "\$\$USER_NAME\$\$" or use single quotes

Try this

$body = str_replace('$$USER_NAME$$', "John Doe", $body); 

Note the difference of double-quotes and single quotes. When PHP sees double-quotes, it would try to parse the value inside it as variables and since your replacement string is $$USER_NAME$$ it your try to find the PHP variable.

You can rename you replacement string to something like __USER_NAME__. This will prevent the confusion.

Here is an article that I have written on PHP double quotes vs single quotes

You are giving the $$USERNAME$$ in double quotes.Which makes php engine to interpret it as a variable.Give it in single quotes and you are raring to go.

As others have pointed out single quotes are probably your problem. You should be able to rewrite your code as a one liner:

echo str_replace('$$USER_NAME$$', 'John Doe', file_get_contents('email/templates/welcome.txt'));

Use this

$body = str_replace('$$USER_NAME$$', "John Doe", $body); 

instead of

$body = str_replace("$$USER_NAME$$", "John Doe", $body);