宝贝我爱你 Good Luck To You!

php根据模版内容生成word

office2007中的新格式启用了zip+xml的方式,所以就可以用php方便的操作word了。原理很简单:调用pclzip.lib.php的类库,进行文本的替换功能。
PS:有时你可能会发现,在替换的过程中,有些值没有替换,其根本的原因在于微软的重复代码的问题,你可以将word另存为htm,查看源代码,就知道word的代码有多么糟糕,然后手动改下htm,再另存为docx文件。这样模板就没什么问题了。

[php]<?php

define("MK_PATH","");	//相对于主文件的位置 末尾加“/”
include_once("pclzip.lib.php");
function createWord($message,$template,$wordfile)
{
	$file_ext=MK_PATH."/apache";
	$sc_rep=array();	//替换源
	$ds_rep=array();	//替换目标
	foreach($message as $key=>$item)
	{
		$sc_rep[]='{'.$key.'}';
		$ds_rep[]=$item;
	}
	if(!is_dir($file_ext))
		mkdir($file_ext);
	$zip=new Pclzip($template);
	$zip->extract($file_ext);
	unset($zip);
	$content=@file_get_contents($file_ext."/word/document.xml");
	//var_dump($content);exit;
	$content=str_replace($sc_rep,$ds_rep,$content);

	@file_put_contents($file_ext."/word/document.xml",$content);
	$zip=new Pclzip($wordfile);
	$zip->create($file_ext."/[Content_Types].xml,".$file_ext."/word,".$file_ext."/docProps,".$file_ext."/_rels",PCLZIP_OPT_REMOVE_PATH,$file_ext);
	//$zip->create("[Content_Types].xml,word,docProps,_rels");

	removeDir($file_ext);

}
function removeDir($dir)
{
	  if(is_dir($dir))
	  {
		  $s=scandir($dir);
		  foreach($s as $i)
			  if($i!="." && $i!="..")
				  removeDir($dir."/".$i);
		  @rmdir($dir);
	  }
	  elseif(is_file($dir))
		  @unlink($dir);
	  else
		  return false;
	  return true;
}
[/php]
作者:johen 分类:技术 浏览:49023 评论:0
留言列表
发表评论
来宾的头像