I have a docx file and I need to replace some text. This is done inside codeigniter framework; here is the code:
$this->load->library(\'word\');
$te
Just add 2 function to the file "TemplateProcessor.php"
public function setValueAdvanced($search_replace)
{
foreach ($this->tempDocumentHeaders as $index => $headerXML) {
$this->tempDocumentHeaders[$index] = $this->setValueForPartAdvanced($this->tempDocumentHeaders[$index], $search_replace);
}
$this->tempDocumentMainPart = $this->setValueForPartAdvanced($this->tempDocumentMainPart, $search_replace);
foreach ($this->tempDocumentFooters as $index => $headerXML) {
$this->tempDocumentFooters[$index] = $this->setValueForPartAdvanced($this->tempDocumentFooters[$index], $search_replace);
}
}
protected function setValueForPartAdvanced($documentPartXML, $search_replace)
{
$pattern = '/(.*?)<\/w:t>/';
$rplStringBeginOffcetsStack = array();
$rplStringEndOffcetsStack = array();
$rplCleanedStrings = array();
$stringsToClean = array();
preg_match_all($pattern, $documentPartXML, $words, PREG_OFFSET_CAPTURE);
$bux_founded = false;
$searching_started = false;
foreach($words[1] as $key_of_words => $word)
{
$exploded_chars = str_split($word[0]);
foreach($exploded_chars as $key_of_chars => $char)
{
if ($bux_founded)
{
if ($searching_started)
{
if ($char == "}")
{
$bux_founded = false;
$searching_started = false;
array_push($rplStringEndOffcetsStack, ($word[1]+mb_strlen($word[0])+6));
}
}
else
{
if ($char == "{")
{
$searching_started = true;
}
else
{
$bux_founded = false;
array_pop($rplStringBeginOffcetsStack);
}
}
}
else
{
if ($char == "$")
{
$bux_founded = true;
array_push($rplStringBeginOffcetsStack, $word[1]-5);
}
}
}
}
for($index=0; $index $replace)
{
if ($rplCleanedStrings[$index] == $key_search)
{
$documentPartXML = str_replace($stringsToClean[$index], "".$replace." ", $documentPartXML);
break;
}
}
}
return $documentPartXML;
}
How to use: Use an array as the only parameter of function "setValueAdvanced", where "key" - a word, that we want to replace, and "value" - phrase we want to paste instead. Important: Inside a MS Word file use "${word_to_replace}" to "mark" a word that we want to replace, but key of an array should be "word_to_replace", without "${}"
Example code:
require_once 'PhpWord/Autoloader.php';
use PhpOffice\PhpWord\Autoloader;
use PhpOffice\PhpWord\Settings;
define('CLI', (PHP_SAPI == 'cli') ? true : false);
define('EOL', CLI ? PHP_EOL : '
');
define('SCRIPT_FILENAME', basename($_SERVER['SCRIPT_FILENAME'], '.php'));
define('IS_INDEX', SCRIPT_FILENAME == 'index');
Autoloader::register();
Settings::loadConfig();
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('your_file_name.docx');
$search_replace_array = array(
'msword_hello'=>'Hello', #inside a MS Word file ${msword_hello} will change to Hello
'msword_world'=>'World' #${msword_world} will change to World
);
$templateProcessor->setValueAdvanced($search_replace_array);
$templateProcessor->saveAs('your_file_name_changed.docx');