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

PHP把网页保存为word文件的三种方法_php实例

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

一、PHP生成word的两种思路或原理

1.利用windows下面的 com组件
2.利用PHP将内容写入doc文件之中
具体实现方法如下。

二、利用windows下面的com组件

原理:com作为PHP的一个扩展类,安装过office的服务器会自动调用word.application的com,可以自动生成文档,PHP官方文档手册:http://www.php.net/manual/en/class.com.php

使用官方实例:

<?php<BR>// starting word<BR>$word = new COM("word.application") or die("Unable to instantiate Word");<BR>echo "Loaded Word, version {$word->Version}\n";<br><br>//bring it to front<BR>$word->Visible = 1;<br><br>//open an empty document<BR>$word->Documents->Add();<br><br>//do some weird stuff<BR>$word->Selection->TypeText("This is a test...");<BR>$word->Documents[1]->SaveAs("Useless test.doc");<br><br>//closing word<BR>$word->Quit();<br><br>//free the object<BR>$word = null;<BR>?>


个人建议:com实例后的方法都需要查找官方文档才知道什么意思,编辑器没有代码提示,非常不方便,另外这个效率也不是很高,不推荐使用

三、利用PHP将内容写入doc文件之中
这个方法又可以分为两种方法

1.生成mht格式(和HTML很相似)写入word
2.纯HTML格式写入word


1)、生成mht格式(和HTML很相似)写入word

/**<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> */<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);   //去掉链接<br><br>    $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>}

这个函数的主要功能其实就是分析HTML代码中的所有图片地址,并且依次下载下来。获取到了图片的内容以后,调用MhtFileMaker类,将图片添加到mht文件中。具体的添加细节,封装在MhtFileMaker类中了。

使用方法1:远程调用

$url= http://www.***.com;<br><br>$content = file_get_contents($url);<br><br>$fileContent = getWordDocument($content,"http://www.yoursite.com/Music/etc/");<BR>$fp = fopen("test.doc", 'w');<BR>fwrite($f<em style="color:transparent">本文来源[email protected]搞@^&代*@码)网9</em><strong>搞代gaodaima码</strong>p, $fileContent);<BR>fclose($fp);<BR>其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址


其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址

使用方法2:本地生成调用

header("Cache-Control: no-cache, must-revalidate"); <BR>header("Pragma: no-cache"); <BR>$wordStr = 'PHP教程网站--php.net'; <BR>$fileContent = getWordDocument($wordStr); <BR>$fileName = iconv("utf-8", "GBK", ‘PHP教程' . '_'. $intro . '_' . rand(100, 999));   <BR>header("Content-Type: application/doc"); <BR>header("Content-Disposition: attachment; filename=" . $fileName . ".doc"); <BR>echo $fileContent;

注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。

<?php<BR>/***********************************************************************<BR>Class:        Mht File Maker<BR>Version:      1.2 beta<BR>Date:         02/11/2007<BR>Author:       Wudi <BR>Description:  The class can make .mht file.<BR>***********************************************************************/<br><br>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;<br><br>    function MhtFile($config = array()){<br><br>    }<br><br>    function SetHeader($header){<BR>        $this->headers[] = $header;<BR>        $key = strtolower(substr($header, 0, strpos($header, ':')));<BR>        $this->headers_exists[$key] = TRUE;<BR>    }<br><br>    function SetFrom($from){<BR>        $this->SetHeader("From: $from");<BR>    }<br><br>    function SetSubject($subject){<BR>        $this->SetHeader("Subject: $subject");<BR>    }<br><br>    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>    }<br><br>    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>    }<br><br>    function SetBaseDir($dir){<BR>        $this->dir_base = str_replace("\\", "/", realpath($dir));<BR>    }<br><br>    function SetFirstPage($filename){<BR>        $this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));<BR>    }<br><br>    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>    }<br><br>    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>    }<br><br>    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>    }<br><br>    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>    }<br><br>    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>    }<br><br>    function CheckFiles(){<BR>        if (count($this->files) == 0) {<BR>            return FALSE;<BR>        } else {<BR>            return TRUE;<BR>        }<BR>    }<br><br>    function GetFile(){<BR>        $this->CheckHeaders();<BR>        if (!$this->CheckFiles()) {<BR>            exit ('No file was added.');<BR>        }<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 $contents;<BR>    }<br><br>    function MakeFile($filename){<BR>        $contents = $this->GetFile();<BR>        $fp = fopen($filename, 'w');<BR>        fwrite($fp, $contents);<BR>        fclose($fp);<BR>    }<br><br>    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>?>

点评:这种方法的缺点是不支持批量生成下载,因为一个页面只能有一个header,(无论远程使用还是本地生成声明header页面只能输出一个header),即使你循环生成,结果还是只有一个word生成(当然你可以修改上面的方式来实现)

2.纯HTML格式写入word

原理:

利用ob_start把html页面先存储起来(解决一下页面多个header问题,可以批量生成),然后在写入doc文档内容利用

代码:

<?php<BR>class word<BR>{ <BR>    function start()<BR>    {<BR>        ob_start();<BR>        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"<BR>        xmlns:w="urn:schemas-microsoft-com:office:word"<BR>        xmlns="http://www.w3.org/TR/REC-html40">';<BR>    }<BR>    function save($path)<BR>    {<br><br>        echo "";<BR>        $data = ob_get_contents();<BR>        ob_end_clean();<br><br>        $this->wirtefile ($path,$data);<BR>    }<br><br>    function wirtefile ($fn,$data)<BR>    {<BR>        $fp=fopen($fn,"wb");<BR>        fwrite($fp,$data);<BR>        fclose($fp);<BR>    }<BR>}


$html = ' <BR><table width="600" cellpadding="6" cellspacing="1" bgcolor="#336699"> <BR><tr bgcolor="White"> <BR>  <td>PHP10086</td> <BR>  <td>http://www.php.net</td> <BR></tr> <BR><tr bgcolor="red"> <BR>  <td>PHP10086</td> <BR>  <td>http://www.php.net</td> <BR></tr> <BR><tr bgcolor="White"> <BR>  <td colspan="2"> <BR>  PHP10086<br> <BR>  最靠谱的PHP技术分享网站 <BR>   <BR>  </td> <BR></tr> <BR></table> <BR>'; <br><br>//批量生成 <BR>for($i=1;$i<=3;$i++){ <BR>    $word = new word(); <BR>    $word->start(); <BR>    //$html = "aaa".$i; <BR>    $wordname = 'PHP教程网站--php.net'.$i.".doc"; <BR>    echo $html; <BR>    $word->save($wordname); <BR>    ob_flush();//每次执行前刷新缓存 <BR>    flush(); <BR>}


个人点评:这种方法效果最好,原因有三个:

第一代码比较简洁,很容易理解
第二是支持批量生成word(这个很重要)
第三是支持完整的html代码


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

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

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

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

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