批量替换word模板,并解决中文乱码问题

require_once './lib/word/PhpWord.php';
require_once './lib/word/PHPWord/IOFactory.php';
$PHPWord = new  PHPWord();
$selsct = Weifanggaizao::find("id >= 1")->order("id ASC")->getAll();

foreach ($selsct as $selscts):       
        $date = strtotime(substr($selscts->sid,6,8));       
        $today = strtotime('today');
        $diff = floor(($today-$date)/86400/365);
        $age = strtotime(substr($selscts->sid,6,8).'+'.$diff.'years')>$today?($diff+1):$diff;

//载入模板文件
$document = $PHPWord->loadTemplate('./docs/aq1.docx');

//替换Word模板文件中的一处内容,这里如果要显示中文,则必须使用iconv函数
$document->setValue('name', iconv('utf-8', 'GB2312//IGNORE', $selscts->name));
$document->setValue('xing_zc', iconv('utf-8', 'GB2312//IGNORE', $selscts->xing_zheng_cun));
$document->setValue('cun_xz', iconv('utf-8', 'GB2312//IGNORE', $selscts->cun_xiao_zu));

$document->setValue('xiang_z', iconv('utf-8', 'GB2312//IGNORE', $selscts->xiang_zhen));
$document->setValue('nong_hxz', iconv('utf-8', 'GB2312//IGNORE', $selscts->nong_hu_ping_kun_xing_zhi));
$document->setValue('yfwmj', iconv('utf-8', 'GB2312//IGNORE', $selscts->yuan_fang_wu_mian_ji));

$document->setValue('sex', iconv('utf-8', 'GB2312//IGNORE', $selscts->sex));
$document->setValue('age', iconv('utf-8', 'GB2312//IGNORE', $age));
$document->setValue('jtrk', iconv('utf-8', 'GB2312//IGNORE', $selscts->jia_ting_ren_kou));

$document->setValue('sid', iconv('utf-8', 'GB2312//IGNORE', $selscts->sid));
$document->setValue('tel', iconv('utf-8', 'GB2312//IGNORE', $selscts->tel));
$document->setValue('xfwmj', iconv('utf-8', 'GB2312//IGNORE', $selscts->xian_fang_wu_mian_ji));

$document->setValue('gzxs', iconv('utf-8', 'GB2312//IGNORE', $selscts->gai_zao_xing_shi));
$document->setValue('yikt', iconv('utf-8', 'GB2312//IGNORE', $selscts->yi_ka_tong));
$filename = './docs/zj/'.$selscts->id.iconv('utf-8', 'GB2312//IGNORE', $selscts->name).'.docx';
//保存Word文档
$document->save($filename);
endforeach;

猜你喜欢

转载自blog.csdn.net/ilwtfqqc/article/details/82769429