При использовании шаблона .docx и замене текста в нем с помощью PHPWord получаются кракозябры вместо русских символов.
utf8_encode() для замены. Перед заменой текста на русский текст необходимо перекодировать его в UTF-8 с помощью utf8_encode().setValue() в PHPWord. В функции setValue() используется str_replace() для замены текста, но она не учитывает кодировку. Можно модифицировать функцию, используя preg_replace() с параметром 'u', чтобы обеспечить поддержку Unicode.public function setValue($macro, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT)
{
foreach ($this->tempDocumentHeaders as $index => $headerXML) {
$this->tempDocumentHeaders[$index] = $this->setValueForPart($this->tempDocumentHeaders[$index], $macro, $replace, $limit);
}
$this->tempDocumentMainPart = $this->setValueForPart($this->tempDocumentMainPart, $macro, $replace, $limit);
foreach ($this->tempDocumentFooters as $index => $headerXML) {
$this->tempDocumentFooters[$index] = $this->setValueForPart($this->tempDocumentFooters[$index], $macro, $replace, $limit);
}
}
protected function setValueForPart($documentPartXML, $search, $replace, $limit)
{
if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${' . $search . '}';
}
// Перекодируем замену текста в UTF-8
$replace = utf8_encode($replace);
// Используем `preg_replace()` с флагом 'u' для поддержки Unicode
return preg_replace("{$regExpDelim}{$escapedSearch}{$regExpDelim}u", $replace, $documentPartXML, $limit);
}