PHP: 使用 .xml 创建 .docx 文档
PHP: creating .docx document using .xml
我正在处理一个需要创建 .docx
文档的项目。我正在使用 PHPWord,加载模板然后保存文件。此文档有很多嵌套表格,PHPWord 在模板中进行一些替换后会破坏表格。
所以我决定将文档另存为 Word XML 文档 (.xml
) 并自己进行替换。我会将文本加载到一个变量中,进行替换,然后另存为新的 word 文档。我的问题是我不知道如何使用 .xml
.
创建 .docx
文档
你能提供一些我可以使用的代码片段吗?
感谢您的帮助
我来到了下面的这段代码。它保存了文件,但是当我尝试使用 word 打开时,它给我无效的文档
$xmlString = simplexml_load_file($this->config->application->fileTemplateFolder.'coi.xml')->asXML();
$xmlString = str_replace('${coi_number}', $coi['application_number'], $xmlString);
$path = $this->config->application->fileTemplateFolder.'test.docx';
$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE);
$zip->addFromString("word/document.xml", $xmlString);
$zip->close();
我是这样解决问题的:
private function CreateWordDocument($xmlString) {
$templateFolder = $this->config->fileTemplateFolder;
if(!endsWith($templateFolder, '/'))
$templateFolder = $templateFolder.'/';
$temp_file = tempnam(sys_get_temp_dir(), 'coi_').'.docx';
copy($templateFolder. 'coi.docx', $temp_file);
$zip = new ZipArchive();
if($zip->open($temp_file)===TRUE) {
$zip->deleteName('word/document.xml');
$zip->addFromString("word/document.xml", $xmlString);
$zip->close();
return $temp_file;
}
else {
return null;
}
}
我正在处理一个需要创建 .docx
文档的项目。我正在使用 PHPWord,加载模板然后保存文件。此文档有很多嵌套表格,PHPWord 在模板中进行一些替换后会破坏表格。
所以我决定将文档另存为 Word XML 文档 (.xml
) 并自己进行替换。我会将文本加载到一个变量中,进行替换,然后另存为新的 word 文档。我的问题是我不知道如何使用 .xml
.
.docx
文档
你能提供一些我可以使用的代码片段吗?
感谢您的帮助
我来到了下面的这段代码。它保存了文件,但是当我尝试使用 word 打开时,它给我无效的文档
$xmlString = simplexml_load_file($this->config->application->fileTemplateFolder.'coi.xml')->asXML();
$xmlString = str_replace('${coi_number}', $coi['application_number'], $xmlString);
$path = $this->config->application->fileTemplateFolder.'test.docx';
$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE);
$zip->addFromString("word/document.xml", $xmlString);
$zip->close();
我是这样解决问题的:
private function CreateWordDocument($xmlString) {
$templateFolder = $this->config->fileTemplateFolder;
if(!endsWith($templateFolder, '/'))
$templateFolder = $templateFolder.'/';
$temp_file = tempnam(sys_get_temp_dir(), 'coi_').'.docx';
copy($templateFolder. 'coi.docx', $temp_file);
$zip = new ZipArchive();
if($zip->open($temp_file)===TRUE) {
$zip->deleteName('word/document.xml');
$zip->addFromString("word/document.xml", $xmlString);
$zip->close();
return $temp_file;
}
else {
return null;
}
}