Following Ivan Krechetov, answer, here is the function that performs the merge (actually just replaces the text) for docx and odt, without the need for an additional library.
function mailMerge($templateFile, $newFile, $row) { if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template return false; // could not duplicate template $zip = new ZipArchive(); if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE) return false; // probably not a docx file $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml'; $data = $zip->getFromName($file); foreach ($row as $key => $value) $data = str_replace($key, $value, $data); $zip->deleteName($file); $zip->addFromString($file, $data); $zip->close(); return true; }
This will replace [Human Name] with Mina and [Human Name] with Mooo:
$replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo'); $newFile = tempnam_sfx(sys_get_temp_dir(), '.dat'); $templateName = 'personinfo.docx'; if (mailMerge($templateName, $newFile, $replacements)) { header('Content-type: application/msword'); header('Content-Disposition: attachment; filename=' . $templateName); header('Accept-Ranges: bytes'); header('Content-Length: '. filesize($file)); readfile($newFile); unlink($newFile); }
Remember that this function can damage the document if the replacement string is too general. Try using verbal replacement strings such as [Person Name].
Matiaan Nov 09 '10 at 21:37 2010-11-09 21:37
source share