The export functionality to the document on the server is extremely useful for converting HTML content to MS word document and download it as a.docx file. The MS word document can be quickly generated with HTML content via PHP.
Converting HTML to MS Word Document used primarily in the web application to generate.doc/.docx file with dynamic HTML data. The most popular file format is the Microsoft word document for exporting dynamic content offline. The JavaScript can be easily used to export HTML content to MS Word functionality. However, if you want to convert dynamic content to Doc, the interaction on the server-side is required. In this tutorial, we will show you step by step process to convert HTML to MS word file using PHP.
Step-1: Create html_to_doc.php file
In the html_to_doc.php file, we will write a custom class library code that helps to generate MS Word file and include the HTML content in Word document using PHP.
title = '';
$this->htmlHead = '';
$this->htmlBody = '';
}
/**
* Set the document file name
*
* @param String $docfile
*/
function setDocFileName($docfile){
$this->docFile = $docfile;
if(!preg_match("/\.doc$/i",$this->docFile) && !preg_match("/\.docx$/i",$this->docFile)){
$this->docFile .= '.doc';
}
return;
}
/**
* Set the document title
*
* @param String $title
*/
function setTitle($title){
$this->title = $title;
}
/**
* Return header of MS Doc
*
* @return String
*/
function getHeader(){
$return = '
'.$this->title.'
'.$this->htmlHead.'
';
return $return;
}
/**
* Return Document footer
*
* @return String
*/
function getFotter(){
return "";
}
/**
* Create The MS Word Document from given HTML
*
* @param String $html :: HTML Content or HTML File Name like path/to/html/file.html
* @param String $file :: Document File Name
* @param Boolean $download :: Wheather to download the file or save the file
* @return boolean
*/
function createDoc($html, $file, $download = false){
if(is_file($html)){
$html = @file_get_contents($html);
}
$this->_parseHtml($html);
$this->setDocFileName($file);
$doc = $this->getHeader();
$doc .= $this->title;
$doc .= $this->htmlBody;
$doc .= $this->getFotter();
if($download){
@header("Cache-Control: ");// leave blank to avoid IE errors
@header("Pragma: ");// leave blank to avoid IE errors
@header("Content-type: application/octet-stream");
@header("Content-Disposition: attachment; filename=\"$this->docFile\"");
echo $doc;
return true;
}else {
return $this->write_file($this->docFile, $doc);
}
}
/**
* Parse the html and remove part if present into html
*
* @param String $html
* @return void
* @access Private
*/
function _parseHtml($html){
$html = preg_replace("//ims", "", $html);
$html = preg_replace("/
