Search code examples
phplaravelphpword

Laravel and phpword possibilities


I use laravel but I think this question is more about php word.

Is it possible with this package to export word with custom text at some points ?

For example, my word template contain three locations to change. So with phpword can I export this template with custom text at this three locations ?

Can I change only part of text or must I change all paragraph ?

Thank for you informations.


Solution

  • You can use the setValue() method to replace the text.

    Depending on which version you are using, version 0.12.0 and up use \PhpOffice\PhpWord\TemplateProcessor

    public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT)
    {
        if (is_array($search)) {
            foreach ($search as &$item) {
                $item = self::ensureMacroCompleted($item);
            }
        } else {
            $search = self::ensureMacroCompleted($search);
        }
        if (is_array($replace)) {
            foreach ($replace as &$item) {
                $item = self::ensureUtf8Encoded($item);
            }
        } else {
            $replace = self::ensureUtf8Encoded($replace);
        }
        if (Settings::isOutputEscapingEnabled()) {
            $xmlEscaper = new Xml();
            $replace = $xmlEscaper->escape($replace);
        }
        $this->tempDocumentHeaders = $this->setValueForPart($search, $replace, $this->tempDocumentHeaders, $limit);
        $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit);
        $this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit);
    }
    

    Link to method -> https://github.com/PHPOffice/PHPWord/blob/develop/src/PhpWord/TemplateProcessor.php#L208

    Before version 0.12.0 use \PhpOffice\PhpWord\Template

    public function setValue($search, $replace, $limit = -1)
    {
        foreach ($this->headerXMLs as $index => $headerXML) {
            $this->headerXMLs[$index] = $this->setValueForPart($this->headerXMLs[$index], $search, $replace, $limit);
        }
        $this->documentXML = $this->setValueForPart($this->documentXML, $search, $replace, $limit);
        foreach ($this->footerXMLs as $index => $headerXML) {
            $this->footerXMLs[$index] = $this->setValueForPart($this->footerXMLs[$index], $search, $replace, $limit);
        }
    }
    

    Link to method -> https://github.com/PHPOffice/PHPWord/blob/e35838f7d7928b2308df3f7f0ef6d49bf96f453c/src/PhpWord/Template.php#L131