Search code examples
phpxmlzipphpword

PHP: creating .docx document using .xml


I'm working on a project where I need to create a .docx document. I was using PHPWord, loading a template and then saving the file. This document has a lot of nested tables and PHPWord is breaking the tables after some replaces in the template.

So I decided to save the document as Word XML document (.xml) and do the replaces myself. I will load the text into a variable, do the replaces and then save as a new word document. My problem is that I don't know how to create a .docx document using a .xml.

Would you have some code snippets I could use?

Thanks for any help


I have come to the piece of code below. It saves the file but when I try to open using word it gives me invalid document

    $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();

Solution

  • Here is how I solved the issue:

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