Read and replace contents in .docx (Word) file

前端 未结 4 603
渐次进展
渐次进展 2020-12-09 12:14

I need to replace content in some word documents based on User input. I am trying to read a template file (e.g. \"template.docx\"), and replace First name {fname}, Address {

4条回答
  •  抹茶落季
    2020-12-09 13:02

    I have same task to edit .doc or .docx file in php, i have use this code for it.

    Reference : http://www.onlinecode.org/update-docx-file-using-php/

        $full_path = 'template.docx';
        //Copy the Template file to the Result Directory
        copy($template_file_name, $full_path);
    
        // add calss Zip Archive
        $zip_val = new ZipArchive;
    
        //Docx file is nothing but a zip file. Open this Zip File
        if($zip_val->open($full_path) == true)
        {
            // In the Open XML Wordprocessing format content is stored.
            // In the document.xml file located in the word directory.
    
            $key_file_name = 'word/document.xml';
            $message = $zip_val->getFromName($key_file_name);               
    
            $timestamp = date('d-M-Y H:i:s');
    
            // this data Replace the placeholders with actual values
            $message = str_replace("{officeaddress}", "onlinecode org", $message);
            $message = str_replace("{Ename}", "ingo@onlinecode.org", $message); 
            $message = str_replace("{name}", "www.onlinecode.org", $message);   
    
            //Replace the content with the new content created above.
            $zip_val->addFromString($key_file_name, $message);
            $zip_val->close();
        }
    

提交回复
热议问题