使用PHP在文件中进行字符串替换

4
我正在为我的Web应用程序编写电子邮件模块,该模块在完成任务(例如注册)时向用户发送HTML电子邮件。由于此电子邮件的格式可能会更改,因此我决定使用模板HTML页面作为电子邮件,并在其中添加自定义标签,例如%fullname%,需要替换它们。
我的函数具有以下格式的数组:array(%fullname%=> 'Joe Bloggs'),其中键是标记标识符,值是需要替换的内容。
我尝试了以下方法:
        $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);
    }

这是最好的方法吗?目前只有1个标签被替换...我走在正确的道路上还是相差甚远?谢谢...
4个回答

5
我认为问题出在您的foreach循环中。以下修正方法可以解决该问题:
foreach($data as $key => $value){
    $repstr = str_replace($key, $value, $line);               
}

另外,我认为这样会更有效:

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

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

0

看起来应该可以工作,但我会使用"file_get_contents()"一次性完成。


0
一个稍微不同的方法是使用PHP的heredocs与字符串插值,例如:
$email = <<<EOD
<HTML><BODY>
Hi $fullname,
  You have just signed up.
</BODY></HTML>
EOD;

这样可以避免使用单独的文件,而且后续进行除简单替换以外的操作也更加容易。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接