【问题标题】:PHP: creating .docx document using .xmlPHP:使用 .xml 创建 .docx 文档
【发布时间】:2017-10-24 23:47:13
【问题描述】:

我正在处理一个需要创建.docx 文档的项目。我正在使用 PHPWord,加载模板,然后保存文件。该文档有很多嵌套表格,在模板中进行一些替换后,PHPWord 正在破坏表格。

所以我决定将文档保存为 Word XML 文档 (.xml) 并自己进行替换。我会将文本加载到变量中,进行替换,然后另存为新的 Word 文档。我的问题是我不知道如何使用.xml 创建.docx 文档。

你有一些我可以使用的代码 sn-ps 吗?

感谢您的帮助


我来到了下面的一段代码。它保存了文件,但是当我尝试使用 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();

【问题讨论】:

  • 你有什么工作尝试
  • 是的,我正在尝试与这篇文章相同的内容:stackoverflow.com/questions/3566677/…,但它对我不起作用
  • 我确信 .docx 文件中的 zip 文件内容比一个 XML 文件要多。您可能需要在新文件的 zip 结构中复制它们。

标签: php xml zip phpword


【解决方案1】:

这是我解决问题的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2013-04-24
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多