php取代word內容的方法:先下載PHPWORD,並解壓縮放到專案下的「extend」;然後載入word檔案;最後使用「$loadtemplate->setValue('account', ' ');”方法替換account內容即可。

PHP使用PHPWORD取代WORD文件內容
利用PHP來取代word裡面的內容。環境是TP5的狀況
下載PHPWORD類,解壓縮放到專案下的,extend/,即:專案/extend/PHPWord
推薦:《PHP教學 》
使用方法:
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');//存储位置
途中替換內容的時候發現亂碼,或是替換不成功!
主要更改了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;
}
}
}
}以上是php如何替換word內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!