当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP生成word文档的三种实现方式

PHP生成word文档的三种实现方式

2017年12月12日  | 移动技术网IT编程  | 我要评论

最近工作遇到关于生成word的问题

现在总结一下生成word的三种方法。

btw:好像只要是标题带php的貌似点击量都不是很高(哥哥我标题还是带上php了),不知道为什么,估计博客园上net技术大牛比较多吧,如果把java,.net,php比作程序员的女友,那么java是oracle门下的大家闺秀,.net微软旗下的名门望族,php则是草根门下的山村野姑,这让我等php草民闷骚男情何以堪情何以堪。。牢骚发完了,正式写吧

php生成word原理

  • 利用windows下面的 com组件
  • 利用php将内容写入doc文件之中

具体实现:

利用windows下面的 com组件

原理:com作为php的一个扩展类,安装过office的服务器会自动调用word.application的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->visible = 1;
 
//open an empty document
$word->documents->add();
 
//do some weird stuff
$word->selection->typetext("this is a test...");
$word->documents[1]->saveas("useless test.doc");
 
//closing word
$word->quit();
 
//free the object
$word = null;
?>

个人建议: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*>(\s*.*?\s*)<\/a>/i' , '$1' , $content); //去掉链接
 
 $images = array();
 $files = array();
 $matches = array();
 //这个算法要求src后的属性值必须使用引号括起来
 if ( preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i',$content ,$matches ) )
 {
  $arrpath = $matches[1];
  for ( $i=0;$i<count($arrpath);$i++)
  {
   $path = $arrpath[$i];
   $imgpath = trim( $path );
   if ( $imgpath != "" )
   {
    $files[] = $imgpath;
    if( substr($imgpath,0,7) == 'http://')
    {
     //绝对链接,不加前缀
    }
    else
    {
     $imgpath = $absolutepath.$imgpath;
    }
    $images[] = $imgpath;
   }
  }
 }
 $mht->addcontents("tmp.html",$mht->getmimetype("tmp.html"),$content);
  
 for ( $i=0;$i<count($images);$i++)
 {
  $image = $images[$i];
  if ( @fopen($image , 'r') )
  {
   $imgcontent = @file_get_contents( $image );
   if ( $content )
    $mht->addcontents($files[$i],$mht->getmimetype($image),$imgcontent);
  }
  else
  {
   echo "file:".$image." not exist!<br />";
  }
 }
  
 return $mht->getfile();
}

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

使用方法:远程调用

url= http://www.***.com;
 
$content = file_get_contents($url);
 
$filecontent = getworddocument($content,"//www.jb51.net/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 = '//www.jb51.net/'; 
$filecontent = getworddocument($wordstr); 
$filename = iconv("utf-8", "gbk", ‘jb51' . '_'. $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
author:  wudi 
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->headers_exists[$key] = true;
 }
 
 function setfrom($from){
  $this->setheader("from: $from");
 }
 
 function setsubject($subject){
  $this->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->setheader("date: $date");
 }
 
 function setboundary($boundary = null){
  if ($boundary == null) {
   $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_multipart_mixed';
  } else {
   $this->boundary = $boundary;
  }
 }
 
 function setbasedir($dir){
  $this->dir_base = str_replace("\\", "/", realpath($dir));
 }
 
 function setfirstpage($filename){
  $this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));
 }
 
 function autoaddfiles(){
  if (!isset($this->page_first)) {
   exit ('not set the first page.');
  }
  $filepath = str_replace($this->dir_base, '', $this->page_first);
  $filepath = 'http://mhtfile' . $filepath;
  $this->addfile($this->page_first, $filepath, null);
  $this->adddir($this->dir_base);
 }
 
 function adddir($dir){
  $handle_dir = opendir($dir);
  while ($filename = readdir($handle_dir)) {
   if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {
    if (is_dir("$dir/$filename")) {
     $this->adddir("$dir/$filename");
    } elseif (is_file("$dir/$filename")) {
     $filepath = str_replace($this->dir_base, '', "$dir/$filename");
     $filepath = 'http://mhtfile' . $filepath;
     $this->addfile("$dir/$filename", $filepath, null);
    }
   }
  }
  closedir($handle_dir);
 }
 
 function addfile($filename, $filepath = null, $encoding = null){
  if ($filepath == null) {
   $filepath = $filename;
  }
  $mimetype = $this->getmimetype($filename);
  $filecont = file_get_contents($filename);
  $this->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->files[] = array('filepath' => $filepath,
        'mimetype' => $mimetype,
        'filecont' => $filecont,
        'encoding' => $encoding);
 }
 
 function checkheaders(){
  if (!array_key_exists('date', $this->headers_exists)) {
   $this->setdate(null, true);
  }
  if ($this->boundary == null) {
   $this->setboundary();
  }
 }
 
 function checkfiles(){
  if (count($this->files) == 0) {
   return false;
  } else {
   return true;
  }
 }
 
 function getfile(){
  $this->checkheaders();
  if (!$this->checkfiles()) {
   exit ('no file was added.');
  }
  $contents = implode("\r\n", $this->headers);
  $contents .= "\r\n";
  $contents .= "mime-version: 1.0\r\n";
  $contents .= "content-type: multipart/related;\r\n";
  $contents .= "\tboundary=\"{$this->boundary}\";\r\n";
  $contents .= "\ttype=\"" . $this->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->files as $file) {
   $contents .= "--{$this->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->boundary}--\r\n";
  return $contents;
 }
 
 function makefile($filename){
  $contents = $this->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;
 }
}
?>

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

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 "</html>";
$data = ob_get_contents();
ob_end_clean();
 
$this->wirtefile ($path,$data);
}
 
function wirtefile ($fn,$data)
{
$fp=fopen($fn,"wb");
fwrite($fp,$data);
fclose($fp);
}
}
$html = ' 
<table width=600 cellpadding="6" cellspacing="1" bgcolor="#336699"> 
<tr bgcolor="white"> 
 <td>php10086</td> 
 <td><a href="http://www.php10086.com" target="_blank" >http://www.php10086.com</a></td> 
</tr> 
<tr bgcolor="red"> 
 <td>php10086</td> 
 <td><a href="http://www.php10086.com" target="_blank" >http://www.php10086.com</a></td> 
</tr> 
<tr bgcolor="white"> 
 <td colspan=2 > 
 php10086<br> 
 最靠谱的php技术博客分享网站 
 <img src="http://www.php10086.com/wp-content/themes/wportal-blue/images/logo.gif"> 
 </td> 
</tr> 
</table> 
'; 
 
//批量生成 
for($i=1;$i<=3;$i++){ 
 $word = new word(); 
 $word->start(); 
 //$html = "aaa".$i; 
 $wordname = 'php淮北的个人网站--php10086.com'.$i.".doc"; 
 echo $html; 
 $word->save($wordname); 
 ob_flush();//每次执行前刷新缓存 
 flush(); 
}

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

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

第三支持完整的html代码

生成了三个word文档:并且内容支持完整的html代码显示,第三种方法强烈推荐

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网