学习使用php实现生成word文档的代码

254 篇文章 9 订阅

学习使用php实现生成word文档的代码

纯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 = '
<style>
@font-face{
font-family:"Times New Roman";
}
@font-face{
font-family:"宋体";
}
@font-face{
font-family:"Wingdings";
}
p.MsoNormal{
mso-style-name:正文;
mso-style-parent:"";
margin:0pt;
margin-bottom:.0001pt;
font-family:\'Times New Roman\';
font-size:12.0000pt;
}
@page{mso-page-border-surround-header:no;
	mso-page-border-surround-footer:no;}@page Section0{
margin-top:72.0000pt;
margin-bottom:72.0000pt;
margin-left:90.0000pt;
margin-right:90.0000pt;
size:612.0000pt 792.0000pt;
layout-grid:18.0000pt;
mso-header-margin:35.4000pt;
mso-footer-margin:35.4000pt;
}
div.Section0{page:Section0;}</style></head><body style="tab-interval:36pt;" ><!--StartFragment--><div class="Section0"  style="layout-grid:18.0000pt;" ><p class=MsoNormal  align=center  style="margin-bottom:20.0000pt;text-indent:8.0000pt;mso-pagination:none;
text-align:center;" ><b style="mso-bidi-font-weight:normal" ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';mso-ansi-font-weight:bold;
font-size:16.0000pt;" ><font face="Times New Roman" >语文考试题</font></span></b><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p></o:p></span></p><p class=MsoNormal ><b style="mso-bidi-font-weight:normal" ><span style="mso-spacerun:\'yes\';font-family:\'Times New ;mso-ansi-font-weight:bold;
Roman\';color:rgb(140,140,140);" ><o:p></o:p></span></p><p class=MsoNormal ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p>&nbsp;</o:p></span></p><p class=MsoNormal ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p>&nbsp;</o:p></span></p></div><!--EndFragment--></body></html>
';

//批量生成 可以不必要批量生成
for ($i = 1; $i <= 3; $i++) {
    $word = new word();
    $word->start();
    $wordname = iconv("UTF-8", "GBK//IGNORE", '哎呀www.qipa250.com_' . $i . "_奇葩.doc");
    echo $html;
    $word->save($wordname);
    ob_flush();//每次执行前刷新缓存
    flush();
}
?>

打开生成的word文档,效果图如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值