Hello, I want to print a letter from a html page. But within the letter, I want it to contain the name of each student on the database. It is the same letter but I want to print/download it having each student's unique name.

3 Years
Discussion Span
Last Post by diafol

You just have a placeholder. BUT how is you letter stored - is it in a plain text file, a DB record or in a php variable or as plain html?
Does it contain preformatting as in hard breaks?
Do you want to be able to download multiple letters at a time from one page, or is it for the student to print off their own letter?

Edited by diafol


The letter is in plain html and it's pre-formatted. And yes I want to be able to download multiple letters at a time from one page.
Thanks for the response.


OK, pretty much like a mailmerge then from your description.

You can use a placeholder:

<p>Dear **NAME**,</p>
<p>Blah blah blah</p>

I'm assuming this letter has a .html extension.

You can get the content of the html file and place it into a variable:

$letter = file_get_contents("path/to/file/filename");

Assuming that you have all the names in an array (let's call it $names), we can do this...

$output = array();
foreach($names as $name){
    $output[] = str_replace("**NAME**", $name, $letter);
$outputFile = implode("<span style='page-break-after: always;'></span>", $output);

That will give you a string ($output) containing multiple letters with the names from the array ($names). Each letter is separated by a "style" page break.

You can show the content thus:

echo $outputFile;

Or you can store the content in a physical file:


Up to you what you do with it. Note, this is purely off the top of my head and has not been tested.


Thank you so much, it worked just fine.
But there's a little challenge, I figured out there are 3 different fields I need to change. One (current academic session: same on all letters, also obtained from the database). The other two are name and registration number of each student. I tried associative array but didn't work.

$output = array();
foreach($records as $student){
    $output[] = str_replace(array("**NAME**","**CAS**","**REG_ID**"), array($student['name'], $student['cas'], $student['reg_id']), $letter);
$outputFile = implode("<span style='page-break-after: always;'></span>", $output);

I'm assuming that you've got all the student records in a var called $records. SHould do the trick if the last example worked.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.