This PHP code defines a function updateDocument() which updates a Microsoft Word document template with specific values and prompts the user to download the updated document. The function first checks if the template document exists and returns an error message if it doesn't. The function then opens the template document using ZipArchive and reads the contents of the document.xml file into a string. Placeholders in the string are replaced with actual data using str_replace(). The function creates a temporary file to hold the updated document, and adds the updated document.xml to the new archive, along with all the other files from the template document. The function prompts the user to save the updated file, deletes the temporary file, and logs the successful update to a log.txt file. If an error occurs during the execution of the code, the error message is logged to the same log.txt file and displayed to the user. The code also includes a form with a submit button to call the updateDocument() function.
Issue is output file is slightly corrupted and I can't understand why, tho it can be recovered and has all the contents. I'm aware that there are api's and etc that can achieve result more efficiently, but my goal is to keep it as vanilla as possible. Code example:
template.docx content:
Name: {name}
E-mail: {email}
Phone: {phone}
Running on windows machine xampp 8.2.0 VS16 As you can see, I did try to log for errors, compared both of the files by opening both (temp docx and output docx) as zip archives, but couldn't spot any obvious differences.
function updateDocument($outputFileName) {
// Check if the template document exists
if (!file_exists('template.docx')) {
error_log('The template document could not be found.', 3, 'log.txt');
echo 'The template document could not be found.';
return;
}
try {
// Open the template document
$zip = new ZipArchive();
$zip->open('template.docx');
// Read the contents of the document.xml file into a string
$documentXml = $zip->getFromName('word/document.xml');
// Replace the placeholders with the actual data
$documentXml = str_replace('{name}', 'John Doe', $documentXml);
$documentXml = str_replace('{email}', 'john.doe@example.com', $documentXml);
$documentXml = str_replace('{phone}', '+371 21112333', $documentXml);
// Close the template document
$zip->close();
// Create a temporary file to hold the updated document
$tempFileName = tempnam(sys_get_temp_dir(), 'updated_document');
$tempZip = new ZipArchive();
$tempZip->open($tempFileName, ZipArchive::CREATE);
// Add the updated document.xml to the new archive
$tempZip->addFromString('word/document.xml', $documentXml);
// Add all the other files from the template document to the new archive
$zip = new ZipArchive();
$zip->open('template.docx');
for ($i = 0; $i < $zip->numFiles; $i++) {
$fileName = $zip->getNameIndex($i);
if ($fileName != 'word/document.xml') {
$tempZip->addFromString($fileName, $zip->getFromIndex($i));
}
}
$zip->close();
// Close the updated document archive
$tempZip->close();
// Prompt the user to save the updated file
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $outputFileName . '"');
readfile($tempFileName);
// Delete the temporary file
unlink($tempFileName);
// Log successful update
error_log('Document updated successfully.', 3, 'log.txt');
} catch (Exception $e) {
// Log the error
error_log('An error occurred: ' . $e->getMessage(), 3, 'log.txt');
// Handle the error
echo 'An error occurred: ' . $e->getMessage();
}
}
// Call the function when the button is pressed
if (isset($_POST['submit'])) {
updateDocument('updated_document.docx');
}?>
<form method='POST'>
<input type='submit' name='submit' value='Submit' />
</form>