Currently, I am using the following to replace Mail Merge fields in a docx file. This replaces mail merge fields «Address_1»
, «Address_2»
etc. with a value from the database and outputs it a new document file.
The issue I am encountering at the moment is if a value from the database is empty the mail merge fields gets replaced with a blank value, which in turn keeps the blank line still in place, thus resulting in something like this in my output file:
private function __parseFile($thefile)
{
$this->_multicount++;
$content = file_get_contents($thefile); ///this is document.xml extracted from the docx file
foreach ($this->searchlist as $placeholder => $val) {
if($val=='' || empty($val)){
$content = str_replace('«'.$placeholder.'»', '', $content); ;
}else{
$content = str_replace('«'.$placeholder.'»', htmlspecialchars($val), $content);
}
}
$newfile = $thefile.'.new'.($this->_multicount);
$fh = fopen($newfile, 'wb');
fwrite($fh, $content);
fclose($fh);
}
What could be done, and is there a better way I can remove the merge fields when the value from the database is empty to get rid of blank lines/paragraphs in the output doc file.
This is something you can solve in Word easily by using rules for your fields. You put all of them in ONE line and define the rules.
If the field is not empty, print a line feed.