Home  >  Article  >  php教程  >  php生成word文档的实例

php生成word文档的实例

WBOY
WBOYOriginal
2016-06-02 09:13:431680browse

php生成word文档比excel感觉要方便多了,他只要设置一下头部信息我们就可以直接使用fopen来实现读取操作,下面看几个例子.

php直接用fopen生成的核心代码如下:

'.你的放的数据.' 

例子,代码如下:

<?php
function word($data, $fileName = &#39;&#39;) {
    if (emptyempty($data)) return &#39;&#39;;
    $data = &#39;<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">&#39; . $data . &#39;</html>&#39;;
    if (emptyempty($fileName)) $fileName = date(&#39;YmdHis&#39;) . &#39;.doc&#39;;
    $fp = fopen($fileName, &#39;wb&#39;);
    fwrite($fp, $data);
    fclose($fp);
}
?>

示例如下:

<?php
$str = &#39;<title>利用php创建word文档</title> 
 <h1>利用php创建word文档</h1> 
 作者:phprm.com 
<hr size=1> 
 <p>如果你打开word.doc,看到了这里的介绍,则说明word文档创建成功了。</p> 
<p> 
<b>版权所有:</b> 
<br>www.phprm.com 
<hr size=1>&#39;;
word($str);
?>

为了方便使用我们把它整理成一个类文件,代码如下:

<?php
class word {
    /*
    @GNU:GPL
    @author axgle <axgle@yahoo.com.cn>
    @date 2005.4.20
    */
    function start() {
        ob_start();
        print &#39;<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">&#39;;
    }
    function save($path) {
        print "</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);
    }
}
?>

使用方法超级简单,代码如下:

<?php
include ("word.php");
$word = new word;
$word->start();
?>

查询mysql数据生成word也是非常的简单我们只要连接数据库,然后把数据库的内容存放在类的$word字段中,然后再利用$word->start();生成即可.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn