如果你的编码格式是utf-8的话就用这个
1.找到 Section.php 的 addText 函数
$givenText = utf8_encode($text);
改成
$givenText = iconv('gbk', 'utf-8', $text);
2.找到template.php这个文件,找到这个,把$replace = utf8_encode($replace);注释,换成 $replace =iconv('gbk', 'utf-8', $replace);
public function setValue($search, $replace) {
if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${'.$search.'}';
} if(!is_array($replace)) {
// $replace = utf8_encode($replace);
$replace =iconv('gbk', 'utf-8', $replace);
}
3.找到PHPWord\Section\Table\Cell.php中的addText()方法,把这行$text = utf8_encode($text);注释掉就可以了
4.输出的时候如果有汉字,就用这个输出
$document->setValue('weekday', iconv("utf-8","gbk",$list['company_name']));
5.保存的时候也一样
$document->save( iconv("utf-8","gbk",'C:/3D定制云_'.$list['company_name'].'.docx'));
6.下载word文档到本地
header("Content-type:text/html;charset=utf-8");
$filename='upload/download/3D定制云_'.$bloc['company_name'].'.docx';
$file_path = iconv("utf-8","gbk",$filename);
$fil_name=$filename;
if (!file_exists($file_path)){
echo "没有该文件";
return;
}else{
ob_clean();
ob_start();
$fp = fopen($file_path,"r");
$file_size = filesize($file_path);
Header("Content-type:application/octet-stream");
Header("Accept-Ranges:bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition:attchment; filename=".$fil_name);
$buffer=1024;
$file_count=0;
while (!feof($fp) && $file_count<$file_size ){
$file_con=fread($fp,$buffer);
$file_count +=$buffer;
echo $file_con;
}
fclose($fp);
ob_end_flush();
}
全部程序
vendor('phpoffice/PHPWord/PHPWord');
$PHPWord = new \PHPWord();
$dir='upload/';
$word='test.docx';
$document = new \PHPWord_Template($dir.$word);
$document->setValue('Value1', $bloc['username']);
$document->setValue('Value2', $bloc['original_password']);
$document->setValue('weekday', iconv("utf-8","gbk",$bloc['company_name']));
$document->save( iconv("utf-8","gbk",'upload/download/3D定制云_'.$bloc['company_name'].'.docx')); header("Content-type:text/html;charset=utf-8");
$filename='upload/download/3D定制云_'.$bloc['company_name'].'.docx';
$file_path = iconv("utf-8","gbk",$filename);
$fil_name=$filename;
if (!file_exists($file_path)){
echo "没有该文件";
return;
}else{
ob_clean();
ob_start();
$fp = fopen($file_path,"r");
$file_size = filesize($file_path);
Header("Content-type:application/octet-stream");
Header("Accept-Ranges:bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition:attchment; filename=".$fil_name);
$buffer=1024;
$file_count=0;
while (!feof($fp) && $file_count<$file_size ){
$file_con=fread($fp,$buffer);
$file_count +=$buffer;
echo $file_con;
}
fclose($fp);
ob_end_flush();
}