I have a Microsoft Word file that I am using as a template. (testingsample.docx) The plan is to use form input values to create a lease agreement. The code I found below works very well for opening up the .docx file and finding and replacing the required strings. The problem is it only works once. The first time it is ran, it overwrites my template. I am trying to find a way to open testingsample.docx, make the required string changes, and save the archive as testingsamplecopy.docx without altering testingsample.docx.
Thanks in advance for any help!
// Create the Object.
$zip = new ZipArchive();
$inputFilename = 'testingsample.docx';
// Open the Microsoft Word .docx file as if it were a zip file... because it is.
if ($zip->open($inputFilename, ZipArchive::CREATE)!==TRUE) {
echo "Cannot open $inputFilename :( "; die;
}
// Fetch the document.xml file from the word subdirectory in the archive.
$xml = $zip->getFromName('word/document.xml');
// Replace the strings
$xml = str_replace("1111","Tenant Name Here",$xml);
$xml = str_replace("2222","Address Here",$xml);
// Write back to the document and close the object
if ($zip->addFromString('word/document.xml', $xml)) { echo 'File written!'; }
else { echo 'File not written. Go back and add write permissions to this folder!l'; }
$zip->close();
header("Location: testingsample.docx");
?>