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.

Recommended Answers

All 5 Replies

Member Avatar for 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?

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.

Member Avatar for diafol

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:

file_put_contents($outputFile,"path/to/new/file/filename");

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.

Member Avatar for diafol
$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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.