PhpWord doesn't replace text

前端 未结 7 1785
闹比i
闹比i 2021-02-14 09:34

I have a docx file and I need to replace some text. This is done inside codeigniter framework; here is the code:

$this->load->library(\'word\');       
$te         


        
7条回答
  •  天涯浪人
    2021-02-14 09:59

    My solution

    function replaceText($element, $variable, $value) {
    $text_class = 'PhpOffice\PhpWord\Element\Text';
    $table_class = 'PhpOffice\PhpWord\Element\Table';
    foreach ($element as $e) {
        if (get_class($e) !== $text_class && method_exists($e, 'getElements')) {
            replaceText($e->getElements(), $variable, $value);
        } elseif (get_class($e) === $text_class && ($match_count = substr_count($e->getText(), $variable))) {
            for ($i = 1; $i <= $match_count; $i++) {
                $e->setText(str_replace($variable, $value, $e->getText()));
            }
        } elseif (get_class($e) === $table_class && ($row_count = count($e->getRows()))) {
            foreach ($e->getRows() as $row) {
                foreach ($row->getCells() as $cell) {
                    replaceText($cell->getElements(), $variable, $value);
                }
            }
        }
    }
    

    }

    $path = public_path('test.docx'); // Path to template document. public_path() Laravel function
    $objReader = \PhpOffice\PhpWord\IOFactory::createReader('Word2007'); // Here can be 'ODText' = .odt, 'Word2007' = .docx etc.
    $docx = $objReader->load($path);
    replaceText($docx->getSections(), '${text}', 'This will be in your document'); // '${text}' can be any text like 'Simple text'
    $docx->save('test2.docx');
    

提交回复
热议问题