Just for a laugh
The question was, how do you do a mail merge in PHP. OK, it was a question that no-one was asking, but I never let the deter me before.
Input Data $ cat inputdata
Tim,Jinkerson,
Ben,De Mora,
Jes,Ferrier,
tjinkers@TJINKERS-GB ~/merge
$ cat template
FAO: .f1 .f2
Dear .f1
Now is the winter of our discontent
made glorious summer by this sun of York
Many thanks
Tim
tjinkers@TJINKERS-GB ~/merge
$ |
The Program
$ cat mymerge.php
$filename = "template";
$mergef = "inputdata";
$fdm = fopen($mergef,"r");
$fnum=1;
$mdata = fgets($fdm, 512);
while (!feof($fdm))
{
list($f1, $f2, $f3, $f4, $f5) = explode(",", $mdata);
$fd = fopen($filename,"r");
$contents = fread ($fd, filesize($filename));
fclose ($fd);
$ofilename = "file.".$f1.".".$f2.".".$fnum;
$contents=str_replace(".f1", $f1, $contents);
$contents=str_replace(".f2", $f2, $contents);
$contents=str_replace(".f3", $f3, $contents);
$contents=str_replace(".f4", $f4, $contents);
$contents=str_replace(".f5", $f5, $contents);
$fdo = fopen($ofilename,"w");
fwrite ($fdo,$contents);
fclose ($fdo);
$fnum++;
$mdata = fgets($fdm, 512);
}
fclose ($mergef);
?>
|
tjinkers@TJINKERS-GB ~/merge
$
For each line of the input data, the program reads the template file as a single string, and then does a replace on the markers for the input date. It writes the results out to a file who's name is based on the input data.
$ php mymerge.php
$ ls
file.Ben.De Mora.2 file.Jes.Ferrier.3 file.Tim.Jinkerson.1 inputdata mymerge.php template
tjinkers@TJINKERS-GB ~/merge
$ cat file.Tim.Jinkerson.1
FAO: Tim Jinkerson
Dear Tim
Now is the winter of our discontent
made glorious summer by this sun of York
Many thanks
Tim
tjinkers@TJINKERS-GB ~/merge |
$
No comments:
Post a Comment