How to replace merge fields in Microsoft word DOCX file using PHP

There are many methods available to replace merge fields in docx file using PHP. In this article, I am going to show a quick way to replace merge fields in Microsoft word documents.

This is very useful when you have documents in template format with variables in form of merge fields and you need to generate multiple files with different values. A good example of merge field replace is to generate invoice from a template where the client details and price are in form of merge fields. So the invoice can be generated for many clients by just changing the client details and price.

While looking around the web I came across TBS (TinyButStrong) template engine. There are many things you can do using TBS template engine. In this article, I am going to explain how to replace merge fields.

You can download the library here http://www.tinybutstrong.com/opentbs.php

You can read the full documentation here http://www.tinybutstrong.com/opentbs.php?doc

It is always better to create a wrapper class to use any library.

Here is an example code


require_once(ROOT . '/tbs/tbs_class.php');
require_once(ROOT . '/tbs/tbs_plugin_opentbs.php');
class Documentmerger {
function mergeDocument($template = '', $data = [], $file = '') {
$TBS = new clsTinyButStrong;
$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
$TBS->LoadTemplate($template, OPENTBS_ALREADY_UTF8);
foreach ($data as $fieldKey => $fieldValues) {
$TBS->MergeField($fieldKey, $fieldValues);
}
$TBS->Show(OPENTBS_FILE, $file);
}
}
$docMergeObj = new Documentmerger();
$mergeFields = [];
$mergeFields[‘common’] = [];
$mergeFields[‘common’][‘date’] = date(‘Y-m-d’);
$docMergeObj->mergeDocument(‘path to template file’, $mergeFields,’path to target new file’);
The above example will replace [common.date] with the current date in the word document.
Hope this helps.

Share this Post