PHP 富文本html代码生成word文档,解决默认Web板式浏览

这段是百度编辑器输入的html代码,自己保存下来


image.png

正文


image.png

然后导出word文档

 public function export($html )
    {
         //传入html代码
        $file = time().rand(10000,99999);

        $path = './Public/tmp/'.$file.'.doc';  //自定义路径
        
        //写入内容
        file_put_contents($path,$html);
        
        //下载文件
       dowmload('/Public/tmp/'.$file.'.doc','管理评审会议纪要_' . changeDateTime(time()));
      
        //删除文件
         @unlink($path);
        //return C('dir_url').'/Public/tmp/'.$file.'.doc';
    }

下载文件的方法

function dowmload($file, $newname = '')
{
//    $filename = getFileUrl($file);
    //C('dir_url') 根目录
    $filename = C('dir_url') . $file;
    if (!file_exists($filename)) {
        echo '<script>alert("文件不存在");history.go(-1);</script>';
        exit();
    }
    $ua = $_SERVER["HTTP_USER_AGENT"];

    $file_disk = pathinfo($filename, PATHINFO_EXTENSION);
    ob_start();
    if ($newname == '') {
        $newname = date('Ymd-H:i:s');
    }
    $file_name = $newname . '.' . $file_disk;

    /**解决中文乱码**/
    $encoded_filename = urlencode($file_name);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);

    //兼容IE11
    if (preg_match("/MSIE/", $ua) || preg_match("/Trident\/7.0/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    } else if (preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $encoded_filename . '"');
    } else {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    }
    /**解决中文乱码** end**/


    header('Content-Type: application/octet-stream');
    header('Accept-Ranges : bytes');
//    header("Content-Disposition:attachment;filename={$newname}.{$file_disk}");//声明作为附件处理和下载后文件的名称
    $size = readfile($filename);
    header("Accept-Length :" . $size);
}

然后发现下载的word文档打开会默认web板式浏览,改回页面视图只要把你富文本的html放在下面html内就OK啦!就这么简单!

          <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">
              <head>
                   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                   <xml><w:WordDocument><w:View>Print</w:View></xml>
                   <script src="includes/js/ztree/js/jquery-1.4.4.min.js" type="text/javascript"></script>
            </head>

          <html>
image.png

如果想要在特定的模板内插入富文本内容可以先预设好模板的HTML在把富文本html插入预设好的html内就行了!

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

推荐阅读更多精彩内容