Grant Collins
Grant Collins

Reputation: 1791

string replace in a file with php

I am writing an email module for my web app that sends a html email to a user on completion of a task such as signing up. Now as the formatting of this email may change I've decided to have a template html page that is the email, with custom tags in it that need to be replaced such as %fullname%.

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

I've 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? as only 1 tag get replaced at the moment... am I on the right path or miles off??

thanks...

Upvotes: 4

Views: 16759

Answers (4)

levanr
levanr

Reputation: 21

//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));

Upvotes: 2

Paolo Bergantino
Paolo Bergantino

Reputation: 488744

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

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

Alternatively, I think this should be more effective:

$file = @file_get_contents("email.html");
if($file) {
    $file = str_replace(array_keys($data), array_values($data), $file);
    print $file;
}

Upvotes: 5

brian-brazil
brian-brazil

Reputation: 34192

A slightly different approach is to use PHP's heredocs combined with string interpolation i.e.:

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

This avoids a separate file, and should make things beyond simple substitution easier later.

Upvotes: 0

GoatRider
GoatRider

Reputation: 1213

That looks like it should work, but I'd use "file_get_contents()" and do it in one big blast.

Upvotes: 0

Related Questions