Read and replace contents in .docx (Word) file

前端 未结 4 615
渐次进展
渐次进展 2020-12-09 12:14

I need to replace content in some word documents based on User input. I am trying to read a template file (e.g. \"template.docx\"), and replace First name {fname}, Address {

4条回答
  •  不知归路
    2020-12-09 12:57

    This is the working version to @addweb-solution-pvt-ltd 's answer.

    //This is the main document in  Template.docx file.
    $file = public_path('template.docx');
    
    $phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
    
    $phpword->setValue('{name}','Santosh');
    $phpword->setValue('{lastname}','Achari');
    $phpword->setValue('{officeAddress}','Yahoo');
    
    $phpword->saveAs('edited.docx');
    

    However, not all of the {name} fields are changing. Not sure why.


    Alternatively:

    // Creating the new document...
    $zip = new \PhpOffice\PhpWord\Shared\ZipArchive();
    
    //This is the main document in a .docx file.
    $fileToModify = 'word/document.xml';
    
    $file = public_path('template.docx');
    $temp_file = storage_path('/app/'.date('Ymdhis').'.docx');
    copy($template,$temp_file);
    
    if ($zip->open($temp_file) === TRUE) {
        //Read contents into memory
        $oldContents = $zip->getFromName($fileToModify);
    
        echo $oldContents;
    
        //Modify contents:
        $newContents = str_replace('{officeaddqress}', 'Yahoo \n World', $oldContents);
        $newContents = str_replace('{name}', 'Santosh Achari', $newContents);
    
        //Delete the old...
        $zip->deleteName($fileToModify);
        //Write the new...
        $zip->addFromString($fileToModify, $newContents);
        //And write back to the filesystem.
        $return =$zip->close();
        If ($return==TRUE){
            echo "Success!";
        }
    } else {
        echo 'failed';
    }
    

    Works well. Still trying to figure how to save it as a new file and force a download.

提交回复
热议问题