Read and replace contents in .docx (Word) file

Santosh Achari picture Santosh Achari · Dec 23, 2016 · Viewed 13k times · Source

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 {address} etc.

template.docx:

To,
The Office,
{officeaddress}
Sub:  Authorization Letter
Sir / Madam,

I/We hereby authorize  to  {Ename}  whose signature is attested here below, to submit application and collect Residential permit for {name}  
Kindly allow him to support our International assignee

{name}                                          {Ename}  

Is there a way to do the same in Laravel 5.3?

I am trying to do with phpword, but I can only see code to write new word files - but not read and replace existing ones. Also, when I simply read and write, the formatting is messed up.

Code:

$file = public_path('template.docx');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);

$phpWord->save('b.docx');

b.docx

To,
The Office,
{officeaddress}

Sub: 
 Authorization Letter
Sir / Madam,


I/We hereby authorize 
 to

{Ename}


whose signature is attested here below, to submit a
pplication and collect Residential permit
 for 
{name}

Kindly allow him to support our International assignee


{name}













{
E
name}

Answer

Santosh Achari picture Santosh Achari · Dec 23, 2016

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.