Skip to content

Instantly share code, notes, and snippets.

@Johnykaushik
Last active January 16, 2020 12:13
Show Gist options
  • Save Johnykaushik/ad0aa55c9c74dfa57fec48a7e443aad3 to your computer and use it in GitHub Desktop.
Save Johnykaushik/ad0aa55c9c74dfa57fec48a7e443aad3 to your computer and use it in GitHub Desktop.
Edit Microsoft word docx file with php
<?php
/**
* Edit docx file with php
* In this file some keyword are replacing with new data
* the docx file is written in archived xml files
* so their is need of accessing the main file of xml which holding the
* actual data of docx file
* but some of our keyword/variable/token are split in xml tags
* It is impossible to search and replace data in file
* So,first combining these splits keywords then
* replacing these keyword with new data
*/
// target filepath and filename
$file="demo.docx";
// check valid .docx file
if(pathinfo($file,PATHINFO_EXTENSION) !== "docx"){
die("File is not a valid docx file");
}
// Create reference variable/object of php zip class
$zip=new ZipArchive();
//opening docx file
if($zip->open($file) == FALSE){
die("Unable to open file");
}
// accessing the document.xml file and its content from subdirectory in the archived file
$xml_content = $zip->getFromName('word/document.xml');
// modifying the keyword(s) in docx file which could be split in internal xml tags
preg_match_all("/\[(.*?)\]/",$xml_content,$match);
// here we can change opening/closing [ ] with {},() or other unique symbol which could be well paired
if(isset($match[0])){
foreach($match[0] as $keyword) {
$new_word[] = strip_tags($keyword);
}
$xml_content = str_replace($match[0],$new_word,$xml_content);
}else {
die("Unable to modify keyword");
}
//file could have multiple words,so grouping keywords in array form
// our key word and [] could be replaced with other symbol but should be same as search symbol
$keywords=array(
"[keyword_1]",
"[key_word_2]",
"[Key_Word 3]",
"[key word4]"
);
// replacement data
$replacement=array(
"newkeyword1",
"newkeyword2",
"newkeyword3",
"newkeyword4"
);
// replacing data with keywords
$xml_content = str_replace($keywords,$replacement,$xml_content);
// write data back to main docx file
if($zip->addFromString('word/document.xml', $xml_content) !== FALSE){
echo "File written successfully";
}else {
echo "Unable to write file";
}
$zip->close();
?>
@ChinigamiHunter
Copy link

Thank you for sharing, and for images there is any way to replace image Or add images to word document using xml ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment