【问题标题】:How to Remove Mail Merge Field from .docx File in PHP?如何从 PHP 中的 .docx 文件中删除邮件合并字段?
【发布时间】:2023-04-02 23:10:01
【问题描述】:

目前,我正在使用以下内容替换 docx 文件中的邮件合并字段。这会将邮件合并字段 «Address_1»«Address_2» 等替换为数据库中的值并将其输出为新的文档文件。

我目前遇到的问题是,如果数据库中的值是空的,邮件合并字段将被替换为空白值,这反过来又使空白行保持在原位,从而在我的输出文件:

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);
    }

可以做什么,有没有更好的方法可以在数据库中的值为空时删除合并字段以消除输出 doc 文件中的空白行/段落。

【问题讨论】:

  • 只是为了仔细检查 - $placeholder 有一个值,但 $val 是 null 还是空?
  • @Luke $placeholder 是 docx 文件中的字段名称,它是在调用库时传递的,例如 ReplaceField("Address_1", $val) //Address_1 = $placeholder 在上述情况下,如果在此过程中 $val 为空,我希望库从文档文件中删除 $placeholder 中传递的合并字段,而不是用空白/空值替换它。

标签: php mailmerge docx-mailmerge


【解决方案1】:

这是您可以通过使用字段规则在 Word 中轻松解决的问题。您将所有这些都放在一行中并定义规则。

如果字段不为空,则打印换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多