首页 >后端开发 >php教程 > 正文

PHP完美生成word文档,可加入html元素

原创2018-05-22 09:18:5701212
php生成word文档在学习中可以经常见到,本篇将介绍一种方法。

PHP生成word文档,网上有很多方法,有调用COM组件生成的,有安装PHP扩展生成的,也有引用第三方类库,如phpword生成的。以下为最简洁的两种方法,无须安装其他,只要你安装了php环境便可以直接生成。

<?phpheader("Content-type:text/html;charset=utf-8");/**
* @desc 方法一、生成word文档

* @param $content
 * @param string $fileName
 */function createWord($content='',$fileName='new_file.doc'){    if(empty($content)){        return;
    }
    $content='<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">
            <meta charset="UTF-8" />'.$content.'</html>';    if(empty($fileName)){
        $fileName=date('YmdHis').'.doc';
    }
    $fp=fopen($fileName,'wb');
    fwrite($fp,$content);
    fclose($fp);
}
$str = '<h1 style="color:red;">我是h1</h1><h2>我是h2</h2>';
createWord($str);/**

* @desc 方法二、生成word文档并下载

* @param $content
 * @param string $fileName
 */function downloadWord($content, $fileName='new_file.doc'){    if(empty($content)){        return;
    }
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$fileName");
    $html = '<html xmlns:v="urn:schemas-microsoft-com:vml"
         xmlns:o="urn:schemas-microsoft-com:office:office"
         xmlns:w="urn:schemas-microsoft-com:office:word" 
         xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" 
         xmlns="http://www.w3.org/TR/REC-html40">';
    $html .= '<head><meta charset="UTF-8" /></head>';    echo $html . '<body>'.$content .'</body></html>';
}
$str = '<h4>表头:</h4>
<table border="1">
<tr>
  <th>姓名</th>
  <th>电话</th>
  <th>电话</th>
</tr>
<tr>
  <td>Bill Gates</td>
  <td>555 77 854</td>
  <td>555 77 855</td>
</tr>
</table>';
downloadWord($str, 'abc.doc');

运行后的效果图

PHP生成word文档

4784711-7a03800ceb3042c6.png

PHP生成word文档

4784711-5eacf3bebe929335.png

本篇介绍了php生成word文档的方法,更多相关内容请关注php中文网。

相关推荐:

ThinkPhp缓存原理及使用详解

Discuz!X/数据库 DB:: 函数操作方法

ThinkPHP框架String类详解

以上就是PHP完美生成word文档,可加入html元素的详细内容,更多请关注php中文网其它相关文章!

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:word php html
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类