利用PHP来替换word里面的内容。环境是TP5的情况

下载PHPWORD[点击下载PHPWord类库],解压缩放到项目下的,extend/,即:项目/extend/PHPWord

使用方法:

require_once './extend/PHPWord/PHPWord.php';
require_once './extend/PHPWord/PHPWord/IOFactory.php';
$PHPWord =  new PHPWord();

$loadtemplate = $PHPWord->loadTemplate('/'.$template.'.docx';);//加载word文件

$loadtemplate->setValue('account', '123');//替换account内容为123
$loadtemplate->setValue('password', '456');//替换password内容为456

$loadtemplate->save('/yourpath/'.md5(time()) .'.docx');//存储位置

途中替换内容的时候发现乱码,或者是替换不成功!

参考过几个网站的资料,感谢那些大神们。

https://segmentfault.com/a/1190000007847203

https://stackoverflow.com/questions/16794294/phpword-doesnt-replace-text/21750677#21750677

主要更改了setValue的替换方法,方法文件所在地:extend/PHPWord/PHPWord/template.php

 

更换为:

public function setValue($search, $replace, $limit=-1) {
        if(substr($search, 0, 1) !== '{' && substr($search, -1) !== '}') {
            $search = '{'.$search.'}';
        }
        
        if(!is_array($replace)) {
            // $replace = utf8_encode($replace);
            //$replace = iconv( 'gbk','utf-8', $replace);
            $replace = str_replace("\n","<w:br />",$replace);
        }
        
        preg_match_all('/\{[^}]+\}/', $this->_documentXML, $matches);
        foreach ($matches[0] as $k => $match) {
            $no_tag = strip_tags($match);
            if ($no_tag == $search) {
                $match = '{'.$match.'}';
                $this->_documentXML = preg_replace($match, $replace, $this->_documentXML, $limit);
                if ($limit == 1) {
                    break;
                }
            }
        }
    }