Created
January 20, 2022 10:26
-
-
Save tihoho/3b5f5c78387b9b9e3665d5b6b673bf91 to your computer and use it in GitHub Desktop.
PHP DOCX replace template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Docx Replacer | |
* | |
* @author Not me | |
* @param string $input Input file path | |
* @param string $output Output file path | |
* @param string $replacements Assoc array of replaces placeholders Ex: ['{NAME}' => 'Alex', ...] | |
*/ | |
function docxReplacer($input, $output, $replacements) { | |
if (copy($input, $output)) { | |
// Create the Object. | |
$zip = new \ZipArchive(); | |
// Open the Microsoft Word .docx file as if it were a zip file... because it is. | |
if ($zip->open($output, \ZipArchive::CREATE) !== true) { | |
return false; | |
} | |
// Fetch the document.xml file from the word subdirectory in the archive. | |
$xml = $zip->getFromName('word/document.xml'); | |
// Replace | |
$xml = str_replace(array_keys($replacements), array_values($replacements), $xml); | |
// Write back to the document and close the object | |
if (false === $zip->addFromString('word/document.xml', $xml)) { | |
return false; | |
} | |
$zip->close(); | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment