How to replace word content in php

藏色散人
Release: 2023-03-03 06:02:02
Original
5899 people have browsed it

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

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","<w:br />",$replace);
        }
        
        preg_match_all(&#39;/\{[^}]+\}/&#39;, $this->_documentXML, $matches);
        foreach ($matches[0] as $k => $match) {
            $no_tag = strip_tags($match);
            if ($no_tag == $search) {
                $match = &#39;{&#39;.$match.&#39;}&#39;;
                $this->_documentXML = preg_replace($match, $replace, $this->_documentXML, $limit);
                if ($limit == 1) {
                    break;
                }
            }
        }
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template