-
-
Save abarke/cee03d78397f7fc0ff528ce940c1680b to your computer and use it in GitHub Desktop.
Edit a Microsoft Word .docx file using PHP and the zip extension.
This file contains 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 | |
$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; | |
} |
Instead of function searchReplaceWordDocument() returning false, is there a way to return the error of some sort, explanation of why it failed?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
open the file in 7zip and find the xml file. Then find exactly the content you wish the replace... e.g. the text inside the bold elements.