How to update docx file using php

How to update docx file using php

In this post we will show you How to update docx file using php, hear for How to update docx file using php we will give you demo and example for implement.

Hear we will show you how to Edit .doc or .docx file using php. Hear we use “client_full_name”, “client_email_address”, “date_today”, “client_website”, “client_mobile_number” in .doc or .docx files

$template_file_name = 'template.docx';

$rand_no = rand(111111, 999999);
$fileName = "results_" . $rand_no . ".docx";

$folder   = "results_";
$full_path = $folder . '/' . $fileName;

try
{
	if (!file_exists($folder))
	{
		mkdir($folder);
	}		
		
	//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("client_full_name",		"onlinecode org",       $message);
		$message = str_replace("client_email_address",	"ingo@onlinecode",	$message);
		$message = str_replace("date_today",			$timestamp,	  			$message);		
		$message = str_replace("client_website",		"www.onlinecode",	$message);		
		$message = str_replace("client_mobile_number",	"+1999999999",		    $message);
		
		//Replace the content with the new content created above.
		$zip_val->addFromString($key_file_name, $message);
		$zip_val->close();
	}
}
catch (Exception $exc) 
{
	$error_message =  "Error creating the Word Document";
	var_dump($exc);
}

Download

Hope this code and post will helped you for implement How to update docx file using php. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org

2 thoughts on “How to update docx file using php”

  1. Help me, i’m a new bie, i practice this code, how come I can only replace 4 or 5 variables, more will not be possible.

Leave a Comment

Your email address will not be published. Required fields are marked *

2  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US