Search code examples
phpmysqlmailmerge

PHP fwrite - which files types work? - linux server


My client has asked me to set up a mail merge structure with an existing database of contacts. They want to be able to upload some sort of Microsoft office document into the system, then I need to be able to generate this file as a printable loop replacing the set fields matching the database.

e.g. Dear %%FIRST_NAME%% would change to Dear John or whatever the record is within the database.

So I am wondering what file type they can export out of Microsoft word to upload into my system that I could use fwrite to string replace these variables and then somehow set up a loop to be able to print these all out.

Thanks


Solution

  • You can use PHPWord for this. http://phpword.codeplex.com/

    It allows you to open the doc/docx file and edit it, although for .doc files you need some compatibility pack (hopefully you can get docx files which are just zips of XML files)

    If you can, I would recommend you using their template system, since that would greatly facilitate your life.

    All you need: instead of doing this:

    Dear %%FIRST_NAME%%, I still listen to your music, man!
    

    Do something like this:

    Dear ${FirstName}, I still listen to your music, man!
    

    Then in your PHP code you can do this:

    <?php
    require_once('PHPWord.php');
    
    $phpWord = new PHPWord();
    $doc = $phpWord->loadTemplate("yourdoc.docx");
    $document->setValue("FirstName", "John Lennon");
    $document->save("yourdoc_modified.docx");
    

    An extra I forgot to say: You don't require running the PHP server on Windows for using this. As long as you have the zip and XML libraries installed, you're all fine.