setValue('account', '');" method to replace account Just the content."/> setValue('account', '');" method to replace account Just the content.">

Home  >  Article  >  Backend Development  >  How to replace word content in php

How to replace word content in php

藏色散人
藏色散人Original
2020-07-23 10:21:505674browse

How to replace word content with php: First download PHPWORD, decompress it and put it in "extend" under the project; then load the word file; finally use "$loadtemplate->setValue('account', ' ');" method can replace the account content.

How to replace word content in php

PHP uses PHPWORD to replace the content of the WORD document

Use PHP to replace the content in word. When the environment is TP5

Download the PHPWORD class, unzip it and put it under the project, extend/, that is: project/extend/PHPWord

Recommendation: "PHP Tutorial

Usage:

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');//存储位置

When replacing content on the way, garbled characters are found, or the replacement is unsuccessful!

Mainly changed the replacement method of setValue. The location of the method file: extend/PHPWord/PHPWord/template.php

was replaced with:

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","",$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;
                }
            }
        }
    }

The above is the detailed content of How to replace word content in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn