Skip to content

Instantly share code, notes, and snippets.

@evgeny-ilyin
Forked from abarke/docx_editor.php
Created April 7, 2024 17:22
Show Gist options
  • Save evgeny-ilyin/2eac07eb5fe1e65601ac6dac0e128d1a to your computer and use it in GitHub Desktop.
Save evgeny-ilyin/2eac07eb5fe1e65601ac6dac0e128d1a to your computer and use it in GitHub Desktop.
Edit a Microsoft Word .docx file using PHP and the zip extension.
<?php
$input = 'original.docx';
$output = 'modified.docx';
$replacements = [
'{test-placeholder-1}' => 'test successful 1',
'{test-placeholder-2}' => 'test successful 2',
'{test-placeholder-3}' => 'test successful 3',
'{test-placeholder-4}' => 'test successful 4',
];
$successful = searchReplaceWordDocument($input, $output, $replacements);
echo $successful ? "Successfully created $output" : 'Failed!';
/**
* Edit a Word 2007 and newer .docx file.
* Utilizes the zip extension http://php.net/manual/en/book.zip.php
* to access the document.xml file that holds the markup language for
* contents and formatting of a Word document.
*
* In this example we're replacing some token strings. Using
* the Office Open XML standard ( https://en.wikipedia.org/wiki/Office_Open_XML )
* you can add, modify, or remove content or structure of the document.
*
* @param string $input
* @param string $output
* @param array $replacements
*
* @return bool
*/
function searchReplaceWordDocument(string $input, string $output, array $replacements): bool
{
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