The string is replaced in the php file

I am writing an email module for my web application that sends an html email to a user when a task is completed, such as registering. Now that the formatting of this letter may change, I decided to create an html page template, which is an email address, with custom tags in it that need to be replaced, for example,% fullname%.

My function has an array in array format (% fullname% => 'Joe Bloggs'); with the key as the tag identifier and the value that it needs to be replaced.

I tried the following:

$fp = @fopen('email.html', 'r'); if($fp) { while(!feof($fp)){ $line = fgets($fp); foreach($data as $value){ echo $value; $repstr = str_replace(key($data), $value, $line); } $content .= $repstr; } fclose($fp); } 

Is this the best way to do this? since only 1 tag is being replaced at the moment ... am i on the right path or miles from ??

thanks...

+4
source share
4 answers

I think the problem is in your foreach. This should fix this:

 foreach($data as $key => $value){ $repstr = str_replace($key, $value, $line); } 

Alternatively, I think this should be more efficient:

 $file = @file_get_contents("email.html"); if($file) { $file = str_replace(array_keys($data), array_values($data), $file); print $file; } 
+5
source
 //read the entire string $str=implode("\n",file('somefile.txt')); $fp=fopen('somefile.txt','w'); //replace something in the file string - this is a VERY simple example $str=str_replace('Yankees','Cardinals',$str); //now, TOTALLY rewrite the file fwrite($fp,$str,strlen($str)); 
+2
source

It seems like it should work, but I would use "file_get_contents ()" and do it with one big bang.

0
source

A slightly different approach is to use PHP heredocs in combination with ie string interpolation:

 $email = <<<EOD <HTML><BODY> Hi $fullname, You have just signed up. </BODY></HTML> EOD; 

This avoids the use of a separate file and makes it easier to work on a simple replacement.

0
source

All Articles