2017-05-24 85 views
0

我正在创建一个项目,我需要创建.docx文档。我正在使用PHPWord,加载模板然后保存文件。这个文档有很多嵌套的表格,PHPWord在模板中取代了一些表格之后就打破了这些表格。PHP:使用.xml创建.docx文档

因此,我决定将文档保存为Word XML文档(.xml),然后替换自己。我将把文本加载到一个变量中,做替换,然后保存为一个新的文档。我的问题是,我不知道如何使用.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(); 
+0

你有什么工作尝试 –

+0

是的,我试着这个职位相同的东西︰https://stackoverflow.com/questions/3566677/problem-saving-edited-zip-archive-docx和它不适合我 –

+0

我敢肯定有更多的zip文件内容在一个.docx文件中,而不仅仅是一个XML文件。您可能需要将它们复制到新文件的zip结构中。 – amphetamachine

回答

0

这是我如何解决这个问题:

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; 
    } 
}