登录  /  注册

PHP生成word文档的三种方法

php中文网
发布: 2016-06-20 13:01:56
原创
1889人浏览过

php生成word的三种方式

PHP生成word原理

利用windows下面的 com组件

利用PHP将内容写入doc文件之中

PHP生成word具体实现:

利用windows下面的 com组件

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

使用官方实例:

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

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

利用PHP将内容写入doc文件之中

这个方法又可以分为两种方法

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

纯HTML格式写入word

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

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

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

 

使用方法:远程调用

url= http://www.***.com;
          
$content = file_get_contents($url);
          
$fileContent = getWordDocument($content,"http://www.yoursite.com/Music/etc/");
$fp = fopen("test.doc", 'w');
fwrite($fp, $fileContent);
fclose($fp);
登录后复制

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

本地生成调用:

header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
$wordStr = 'PHP淮北的个人网站--PHP10086.com';
$fileContent = getWordDocument($wordStr);
$fileName = iconv("utf-8", "GBK", ‘PHP淮北’ . '_'. $intro . '_' . rand(100, 999));  
header("Content-Type: application/doc");
header("Content-Disposition: attachment; filename=" . $fileName . ".doc");
echo $fileContent;
登录后复制

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

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

2.纯HTML格式写入word

原理:

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

代码:

<?php class word
{
function start()
{
ob_start();
echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">';
}
function save($path)
{
    
echo "
登录后复制
智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号