• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

使用PHP导出Word文档的原理和实例_php实例

php 搞代码 3年前 (2022-01-25) 32次浏览 已收录 0个评论

原理

一般,有2种方法可以导出doc文档,一种是使用com,并且作为php的一个扩展库安装到服务器上,然后创建一个com,调用它的方法。安装过office的服务器可以调用一个叫word.application的com,可以生成word文档,不过这种方式我不推荐,因为执行效率比较低(我测试了一下,在执行代码的时候,服务器会真的去打开一个word客户端)。理想的com应该是没有界面的,在后台进行数据转换,这样效果会比较好,但是这些扩展一般需要收费。
第2种方法,就是用PHP将我们的doc文档内容直接写入一个后缀为doc的文件中即可。使用这种方法不需要依赖第三方扩展,而且执行效率较高。
word本身的功能还是很强大的,它可以打开html格式的文件,并且能够保留格式,即使后缀为doc,它也能识别正常打开。这就为我们提供了方便。但是有一个问题,html格式的文件中的图片只有一个地址,真正的图片是保存在其他地方的,也就是说,如果将HTML格式写入doc中,那么doc中将不能包含图片。那我们如何创建包含图片的doc文档呢?我们可以使用和html很接近的mht格式。
mht格式和html很类似,只不过在mht格式中,外部链接进来的文件,比如图片、Javascript、CSS会被base64进行编码存储。因此,单个mht文件就可以保存一个网页中的所有资源,当然,相比html,它的尺寸也会比较大。
mht格式能被word识别吗?我将一个网页保存成mht,然后修改后缀名为doc,再用word打开,OK,word也可以识别mht文件,并且可以显示图片。
好了,既然doc可以识别mht,下面就是考虑如何将图片放入mht了。由于html代码中的图片的地址都是写在img标签的src属性中,因此,只要提取html代码中的src属性值,就可以获得图片地址。当然,有可能您获取到的是相对路径,没关系,加上URL的前缀,改成绝对路径就可以了。有了图片地址,我们就可以通过file_get_content函数获取到图片文件的具体内容,然后调用base64_encode函数将文件内容编码成base64编码,最后插入到mht文件的合适位置即可。
最后,我们有两种方法将文件发送给客户端,一种是先在服务器端生成一个doc文档,然后将这个doc文档的地址记录下来,最后,通过header(“location:xx.doc”);就可以让客户端下载这个doc。还有一种是直接发送html请求,修改HTML协议的header部分,将它的content-type设置为application/doc,将content-disposition设置为attachment,后面跟上文件名,发送完html协议以后,直接将文件内容发送给客户端,也可以让客户端下载到这个doc文档。

实现

通过以上的原理介绍,相信大家应该对实现的过程有个初步的了解了,下面我给出一个导出函数,这个函数可以将HTML代码导出成一个mht文档,参数有3个,其中后2个为可选参数
content:要转换的HTML代码
absolutePath: 如果HTML代码中的图片地址都是相对路径,那么这个参数就是HTML代码中缺少的绝对路径。
isEraseLink:是否去掉HTML代码中的超链接
返回值为mht的文件内容,您可以通过file_put_content将它保存成后缀名为doc的文件
这个函数的主要功能其实就是分析HTML代码中的所有图片地址,并且依次下载下来。获取到了图片的内容以后,调用MhtFileMaker类,将图片添加到mht文件中。具体的添加细节,封装在MhtFileMaker类中了。

/**<BR> * 根据HTML代码获取word文档内容<BR> * 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源<BR> * 该函数依赖于类MhtFileMaker<BR> * 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取<BR> * <BR> * @param string $content HTML内容<BR> * @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束<BR> * @param bool $isEraseLink 是否去掉HTML内容中的链接<BR>* by www.php.net<BR> */<BR>function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )<BR>{<BR>    $mht = new MhtFileMaker();<BR>    if ($isEraseLink)<BR>        $content = preg_replace('/(\s*.*?\s*)<\/a>/i' , '$1' , $content);   //去掉链接</P><P>    $images = array();<BR>    $files = array();<BR>    $matches = array();<BR>    //这个算法要求src后的属性值必须使用引号括起来<BR>    if ( preg_match_all('//i',$content ,$matches ) )<BR>    {<BR>        $arrPath = $matches[1];<BR>        for ( $i=0;$i<count($arrPath);$i++)<BR>        {<BR>            $path = $arrPath[$i];<BR>            $imgPath = trim( $path );<BR>            if ( $imgPath != "" )<BR>            {<BR>                $files[] = $imgPath;<BR>                if( substr($imgPath,0,7) == 'http://')<BR>                {<BR>                    //绝对链接,不加前缀<BR>                }<BR>                else<BR>                {<BR>                    $imgPath = $absolutePath.$imgPath;<BR>                }<BR>                $images[] = $imgPath;<BR>            }<BR>        }<BR>    }<BR>    $mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);<br><br>    for ( $i=0;$i<count($images);$i++)<BR>    {<BR>        $image = $images[$i];<BR>        if ( @fopen($image , 'r') )<BR>        {<BR>            $imgcontent = @file_get_contents( $image );<BR>            if ( $content )<BR>                $mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent);<BR>        }<BR>        else<BR>        {<BR>            echo "file:".$image." not exist!<br />";<BR>        }<BR>    }<br><br>    return $mht->GetFile();<BR>}<BR>


使用方法:

$fileContent = getWordDocument($content,"http://www.php.net/Music/etc/");<BR>$fp = fopen("test.doc", 'w');<BR>fwrite($fp, $fileContent);<BR>fclose($fp);<BR>

其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址
注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。

<?php<BR>/***********************************************************************<BR>Class:        Mht File Maker<BR>Version:      1.2 beta<BR>Author:       Wudi <BR>Description:  The class can make .mht file.<BR>***********************************************************************/</P><P>class MhtFileMaker{<BR>    var $config = array();<BR>    var $headers = array();<BR>    var $headers_exists = array();<BR>    var $files = array();<BR>    var $boundary;<BR>    var $dir_base;<BR>    var $page_first;</P><P>    function MhtFile($config = array()){</P><P>    }</P><P>    function SetHeader($header){<BR>        $this->headers[] = $header;<BR>        $key = strtolower(substr($header, 0, strpos($header, ':')));<BR>        $this->headers_exists[$key] = TRUE;<BR>    }</P><P>    function SetFrom($from){<BR>        $this->SetHeader("From: $from");<BR>    }</P><P>    function SetSubject($subject){<BR>        $this->SetHeader("Subject: $subject");<BR>    }</P><P>    function SetDate($date = NULL, $istimestamp = FALSE){<BR>        if ($date == NULL) {<BR>            $date = time();<BR>        }<BR>        if ($istimestamp == TRUE) {<BR>            $date = date('D, d M Y H:i:s O', $date);<BR>        }<BR>        $this->SetHeader("Date: $date");<BR>    }</P><P>    function SetBoundary($boundary = NULL){<BR>        if ($boundary == NULL) {<BR>            $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';<BR>        } else {<BR>            $this->boundary = $boundary;<BR>        }<BR>    }</P><P>    function SetBaseDir($dir){<BR>        $this->dir_base = str_replace("\\", "/", realpath($dir));<BR>    }</P><P>    function SetFirstPage($filename){<BR>        $this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));<BR>    }</P><P>    function AutoAddFiles(){<BR>        if (!isset($this->page_first)) {<BR>            exit ('Not set the first page.');<BR>        }<BR>        $filepath = str_replace($this->dir_base, '', $this->page_first);<BR>        $filepath = 'http://mhtfile' . $filepath;<BR>        $this->AddFile($this->page_first, $filepath, NULL);<BR>        $this->AddDir($this->dir_base);<BR>    }</P><P>    function AddDir($dir){<BR>        $handle_dir = opendir($dir);<BR>        while ($filename = readdir($handle_dir)) {<BR>            if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {<BR>                if (is_dir("$dir/$filename")) {<BR>                    $this->AddDir("$dir/$filename");<BR>                } elseif (is_file("$dir/$filename")) {<BR>                    $filepath = str_replace($this->dir_base, '', "$dir/$filename");<BR>                    $filepath = 'http://mhtfile' . $filepath;<BR>                    $this->AddFile("$dir/$filename", $filepath, NULL);<BR>                }<BR>            }<BR>        }<BR>        closedir($handle_dir);<BR>    }</P><P>    function AddFile($filename, $filepath = NULL, $encoding = NULL){<BR>        if ($filepath == NULL) {<BR>            $filepath = $filename;<BR>        }<BR>        $mimetype = $this->GetMimeType($filename);<BR>        $filecont = file_get_contents($filename);<BR>        $this->AddContents($filepath, $mimetype, $filecont, $encoding);<BR>    }</P><P>    function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){<BR>        if ($encoding == NULL) {<BR>            $filecont = chunk_split(base64_encode($filecont), 76);<BR>            $encoding = 'base64';<BR>        }<BR>        $this->files[] = array('filepath' => $filepath,<BR>                               'mimetype' => $mimetype,<BR>                               'filecont' => $filecont,<BR>                               'encoding' => $encoding);<BR>    }</P><P>    function CheckHeaders(){<BR>        if (!array_key_exists('date', $this->headers_exists)) {<BR>            $this->SetDate(NULL, TRUE);<BR>        }<BR>        if ($this->boundary == NULL) {<BR>            $this->SetBoundary();<BR>        }<BR>    }</P><P>    function CheckFiles(){<BR>        if (count($this->files) == 0) {<BR>            return FALSE;<BR>        } else {<BR>            return TRUE;<BR>        }<BR>    }</P><P>    function GetFile(){<BR>        $this->CheckHeaders();<BR>        if (!$this->CheckFiles()) {<BR>            exit ('No file was added.');<BR>        } //www.php.net<BR>        $contents = implode("\r\n", $this->headers);<BR>        $contents .= "\r\n";<BR>        $contents .= "MIME-Version: 1.0\r\n";<BR>        $contents .= "Content-Type: multipart/related;\r\n";<BR>        $contents .= "\tboundary=\"{$this->boundary}\";\r\n";<BR>        $contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n";<BR>        $contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n";<BR>        $contents .= "\r\n";<BR>        $contents .= "This is a multi-part message in MIME format.\r\n";<BR>        $contents .= "\r\n";<BR>        foreach ($this->files as $file) {<BR>            $contents .= "--{$this->boundary}\r\n";<BR>            $contents .= "Content-Type: $file[mimetype]\r\n";<BR>            $contents .= "Content-Transfer-Encoding: $file[encoding]\r\n";<BR>            $contents .= "Content-Location: $file[filepath]\r\n";<BR>            $contents .= "\r\n";<BR>            $contents .= $file['filecont'];<BR>            $contents .= "\r\n";<BR>        }<BR>        $contents .= "--{$this->boundary}--\r\n";<BR>        return $content<div style="color:transparent">本&文来源gaodai^.ma#com搞#代!码网</div><strong>搞gaodaima代码</strong>s;<BR>    }</P><P>    function MakeFile($filename){<BR>        $contents = $this->GetFile();<BR>        $fp = fopen($filename, 'w');<BR>        fwrite($fp, $contents);<BR>        fclose($fp);<BR>    }</P><P>    function GetMimeType($filename){<BR>        $pathinfo = pathinfo($filename);<BR>        switch ($pathinfo['extension']) {<BR>            case 'htm': $mimetype = 'text/html'; break;<BR>            case 'html': $mimetype = 'text/html'; break;<BR>            case 'txt': $mimetype = 'text/plain'; break;<BR>            case 'cgi': $mimetype = 'text/plain'; break;<BR>            case 'php': $mimetype = 'text/plain'; break;<BR>            case 'css': $mimetype = 'text/css'; break;<BR>            case 'jpg': $mimetype = 'image/jpeg'; break;<BR>            case 'jpeg': $mimetype = 'image/jpeg'; break;<BR>            case 'jpe': $mimetype = 'image/jpeg'; break;<BR>            case 'gif': $mimetype = 'image/gif'; break;<BR>            case 'png': $mimetype = 'image/png'; break;<BR>            default: $mimetype = 'application/octet-stream'; break;<BR>        }<BR>        return $mimetype;<BR>    }<BR>}<BR>?><BR>

上面讨论了通过mht文件,来实现PHP导出doc格式的。这种方法可以解决一个难题,就是使导出的doc文件中包含图片,当然,如果您要包含更多的内容,比如CSS样式表,只需要用正则表达式分析HTML代码中的link标签,提取css样式文件的地址,然后读取并编码成base64,最后加入到mht文件中就可以了。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用PHP导出Word文档的原理和实例_php实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址