Word 文档文件格式
如果在 createDoc() 方法中传递的文件名中未提及扩展名,则默认将其保存为 .doc 文件格式。
要将 Word 文档另存为 .docx 文件格式,请指定带有扩展名的文件名。
$htd->createDoc($htmlContent, "my-document.docx");
从 HTML 文件创建 Word 文档
我们可以通过指定 HTML 文件名将 HTML 文件内容转换为 Word 文档。
$htd->createDoc("source.html", "my-document");
在本教程中,我们将向我们展示如何在 PHP 中将 HTML 转换为 MS Word 文档。
HTML 转 Word (DOC/DOCX) 库
HTML_TO_DOC 类是一个自定义库,可帮助生成 MS Word 文档并使用 PHP 在 Word 文档中包含 HTML 格式的内容。
- setDocFileName() - 设置文档文件名。
- setTitle() - 设置文档标题。
- getHeader() - 创建文档的标题部分。
- getFotter() - 创建文档的页脚部分。
- createDoc() - 创建 .dcox 格式的 word 文档。
- _parseHtml() - 从源解析和过滤 HTML。
- write_file() - 在 word 文件中插入内容。
<?php /** * 将html格式转换为doc格式 */ class HTML_TO_DOC { var $docFile = ''; var $title = ''; var $htmlHead = ''; var $htmlBody = ''; /** * Constructor * * @return void */ function __construct(){ $this->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 = <<<EOH <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 9"> <meta name=Oroirnator content="Microsoft Word 9"> <!--[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--> <title>$this->title</title> <!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Print</w:View> <w:DoNotHyphenateCaps/> <w:PunctuationKerning/> <w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing> <w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing> </w:WordDocument> </xml><![endif]--> <style> <!-- /* Font Definitions */ @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:7.5pt; mso-bidi-font-size:8.0pt; font-family:"Verdana"; mso-fareast-font-family:"Verdana";} p.small {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:1.0pt; mso-bidi-font-size:1.0pt; font-family:"Verdana"; mso-fareast-font-family:"Verdana";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1032"> <o:colormenu v:ext="edit" strokecolor="none"/> </o:shapedefaults></xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif]--> $this->htmlHead </head> <body> EOH; return $return; } /** * Return Document footer * * @return String */ function getFotter(){ return "</body></html>"; } /** * 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->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 <head></head> part if present into html * * @param String $html * @return void * @access Private */ function _parseHtml($html){ $html = preg_replace("/<!DOCTYPE((.|\n)*?)>/ims", "", $html); $html = preg_replace("/<script((.|\n)*?)>((.|\n)*?)<\/script>/ims", "", $html); preg_match("/<head>((.|\n)*?)<\/head>/ims", $html, $matches); $head = !empty($matches[1])?$matches[1]:''; preg_match("/<title>((.|\n)*?)<\/title>/ims", $head, $matches); $this->title = !empty($matches[1])?$matches[1]:''; $html = preg_replace("/<head>((.|\n)*?)<\/head>/ims", "", $html); $head = preg_replace("/<title>((.|\n)*?)<\/title>/ims", "", $head); $head = preg_replace("/<\/?head>/ims", "", $head); $html = preg_replace("/<\/?body((.|\n)*?)>/ims", "", $html); $this->htmlHead = $head; $this->htmlBody = $html; return; } /** * Write the content in the file * * @param String $file :: File name to be save * @param String $content :: Content to be write * @param [Optional] String $mode :: Write Mode * @return void * @access boolean True on success else false */ function write_file($file, $content, $mode = "w"){ $fp = @fopen($file, $mode); if(!is_resource($fp)){ return false; } fwrite($fp, $content); fclose($fp); return true; } }
使用PHP将 HTML 转换为 Word 文档
下面的示例代码使用 HTML_TO_DOC 类将 HTML 内容转换为 MS Word 文档并保存为“.docx”文件。
- 加载并初始化 HTML_TO_DOC 类。
//Load library include_once 'HtmlToDoc.class.php'; //Initialize class $htd = new HTML_TO_DOC();
- 指定要转换的 HTML 内容。
$htmlContent = ' <h1>Hello World!</h1> <p>This document is created from HTML.</p>';
- 调用'createDoc()'函数将HTML 转换为Word 文档。
- 指定保存 HTML 内容的变量 ( '$htmlContent' )。
- 指定文档名称以保存 word 文件 ( 'my-document' )。
$htd->createDoc($htmlContent, "my-document");
下载word文件:
要下载 word 文件,请将“createDoc()”的第三个参数设置为 TRUE。
$htd->createDoc($htmlContent, "my-document", 1);
日期:2020-06-02 22:15:27 来源:oir作者:oir