0

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: enter image description here

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.

Arfan
  • 17
  • 6
  • 1
    Just to double check - `$placeholder` has a value, but `$val` is null or empty? – Luke Sep 15 '20 at 15:00
  • @Luke $placeholder is the field name in the docx file, it is passed when the library is called e.g `ReplaceField("Address_1", $val) //Address_1 = $placeholder` In the above case if $val is empty during the process I want the library to get rid of the merge field passed in $placeholder from the document file, instead of replacing it with a blank/empty value. – Arfan Sep 15 '20 at 15:02

1 Answers1

0

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.

Christoph S.
  • 585
  • 3
  • 16