这里是文章模块栏目内容页
php修改替换word文档内容的两种方法

本文主要描述用php的COM类 处理word文档的方法,和用把word文档转换成大纲模式的html页面后通过文本查找替换的方式 处理word内容的两种方法。


方法1,把word转换为html再替换内容:

ob_start();//开启缓存
 
print'';//输出头部
 
$content = file_get_contents
 
(S_ROOT.'./temp/word/index.htm');//取得模板内容
$content = str_replace('<{jzydt_company_name}>',"400电话",$content);//经过一列替换操作,将会模板里的标签替换为接受的值,如果感觉有必要的话,用正则替换也行,但我不建议动不动就用正则,能不用就不用吧!
$docname = 'index.doc';//生成保存的文件名,后缀为doc
echo $content;//将替换后的内容输出到缓存中
print "";
$data = ob_get_contents();
ob_end_clean();
$fp=fopen(S_ROOT.'./temp/word/'.$docname,"wb");//以二进制写权限打开一个新的word文件,即新建
fwrite($fp,$data);//将内容写入并 保存
fclose($fp);

方法二,通过php的COM类 操作word文档 进行内容替换。

<?
// 建立一个指向新COM组件的索引
$word = new COM(”word.application”) or die(”Can't start Word!”);
// 显示目前正在使用的Word的版本号
//echo “Loading Word, v. {$word->Version}<br>”;
// 把它的可见性设置为0(假),如果要使它在最前端打开,使用1(真)
// to open the application in the forefront, use 1 (true)
//$word->Visible = 0;
 
//打?一个文档
$word->Documents->OPen(”d:\index\index.doc”);
//读取文档内容
 
$test= $word->ActiveDocument->content->Text;
 
echo $test;
echo “<br>”;
//将文档中需要换的变量更换一下
$test=str_replace(”<{变量}>”,”这是变量”,$test);
echo $test;
$word->Documents->Add();
// 在新文档中添加文字
$word->Selection->TypeText(”$test”);
//把文档保存在目录中
$word->Documents[1]->SaveAs(”d:/index/index.doc”);
// 关闭与COM组件之间的连接
$word->Quit();
?>

好了,本文内容全部结束,感谢您的阅读,希望对 您 有所帮助。