function compile_template($template_file, $output_file, $data) { $tmp_file_name = tempnam(sys_get_temp_dir(), 'tmp_php_'); copy($template_file, $tmp_file_name); $zip = new ZipArchive(); if ($zip->open($tmp_file_name)) { $settings_content = $zip->getFromName('word/settings.xml'); $settings = new SimpleXMLElement($settings_content); $doc_vars = $settings->{'w:docVars'}; if (!$doc_vars) { $doc_vars = $settings->addChild('w:docVars'); } foreach ($data as $key => $value) { $child = $doc_vars->addChild('w:docVar'); $child->addAttribute('w:name', $key, 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $child->addAttribute('w:val', $value, 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); } $update_fields = $settings->{'w:updateFields'}; if (!$update_fields) { $update_fields = $settings->addChild('w:updateFields'); } $update_fields->addAttribute('w:val', 'true', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $zip->deleteName('word/settings.xml'); $zip->addFromString('word/settings.xml', $settings->asXML()); } $zip->close(); if ($output_file == 'php://output') { header('Cache-Control: max-age=0'); header('Content-Description: File Transfer'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($tmp_file_name)); readfile($tmp_file_name); } else { file_put_contents($output_file, file_get_contents($tmp_file_name)); } unlink($tmp_file_name); }использование
// Для того чтобы скачать скомпилированный шаблон header('Content-Disposition: attachment; filename="Договор.docx"'); compile_template('document.docx', 'php://output', array('ID' => '123')); // или если необходимо сохранить на сервере compile_template('document.docx', 'compiled_document.docx', array('ID' => '123'));
PS. не говорю что это конечный вариант... данная функция ещё будет мной дорабатываться, но это уже рабочий вариант. Боюсь что потом могу забыть поделиться, поэтому делюсь сейчас.