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

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

<?php

header("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文档

PHP生成word文档

转载请标明原文链接: https://www.jianshu.com/p/3a59904c6898
更多精彩请访问个人博客:https://www.whmblog.cn/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,292评论 25 708
  • awesome-php 收集整理一些常用的PHP类库, 资源以及技巧. 以便在工作中迅速的查找所需... 这个列表...
    guanguans阅读 4,503评论 0 34
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,241评论 4 61
  • 大雪过后 降雪的几率增大 天气也会愈发变得寒冷 狗狗过冬也将面临一些小危险 下面是天天训狗整理的几点宠物过冬小贴士...
    天天训狗阅读 386评论 0 0
  • 昨天孩子生病 ,去医院吊水,那个哭的呦,心疼。今天接着吊水,因为老是哭白白多唉扎了4针,看着孩子哭的那个声音,心里...
    忽而之颠阅读 166评论 0 0