php生成word文件并下载

业务需求常常会有导出功能,大部分都是导出excel(如今使用 https://github.com/PHPOffice/PhpSpreadsheet导出),最近须要一个word导出的功能,忽然想到好像以前历来没有作过导出word的.php

网上导出word好像有多种,咱们取最简单的一种,就是以html的形式写入文件并保存html

下面上代码:git

<?php
//建立word.php
$content = '';
//此处为防止乱码,设置meta utf8编码
$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"><head><STYLE>BR.page { page-break-after: always }</STYLE><meta charset="UTF-8"></head><body>';
$content .= "<b><center>xxx</center></b>";
//试一下颜色样式
$content .= "<p style='color:red'>交易合同号:".rand(0,10000)."</p>";
$content .= "<p>甲方(出让方):aaa公司</p>";
$content .= "<p>丙方(托管方):bbb公司</p>";
$content .= "<p>鉴于</p>";
$content .= "<p>第xx条 协议生效</p>";
$content .= "<p>第xx条 1213</p>";
$content .= '</body></html>';

//windows下文件名不要有中文
$filename = 'word' . date('Ymd', time()) . uniqid("_") . '.doc';
$path_dir = './uploads/' . date("Y-m-d") . "/";//目录
if (!is_dir($path_dir)) mkdir($path_dir, 0777, true);
$fp = fopen($path_dir  . $filename, 'w');
fwrite($fp, $content);
fclose($fp);

header('location:'.$path_dir  . $filename);

打开php内置服务器github

,以后浏览器访问 http://127.0.0.1:7788/word.phpwindows

就能够下载了 浏览器

打开下载文件 颜色也是被设置红色的服务器

一切正常,结束.编码

原文地址 https://blog.moyixi.cn/index.php/archives/87/excel

相关文章
相关标签/搜索