PHP 导出简单文本内容(word txt等)

时间:2024-08-10 23:03:56

PHP导出word文件,简单拓展可导出其他文本类文件

 /**
* PHP 导出简单文本内容(word txt等)
* @param $content mixed 导出内容 (文本string / html代码)
* @param $filename string 需保存文件名
* @param string $extension 文件类型 (doc docx txt xml)
*/
function export_html_to_word($content, $filename, $extension = 'doc')
{
ob_start(); $_export_content = '';
if ($extension == 'doc' || $extension == 'docx') {
$_export_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">';
} $_export_content .= $content; if ($extension == 'doc' || $extension == 'docx') $_export_content .= '</html>'; echo $_export_content; ob_get_contents(); if ($extension == 'doc' || $extension == 'docx') header('Content-type:application/word');
header('Content-Disposition: attachment; filename=' . $filename . '.' . $extension); ob_flush();
flush();
} $html = '<b style="color: red">你看我哪里像好人</b>'; $wordname = 'test-file'; export_html_to_word($html, $wordname);

附:mpdf导出PDF

 /**
* PHP 使用 mpdf 导出PDF文件
* @param $content string PDF文件内容 若为html代码,css内容分离 非id,class选择器可能失效,解决办法直接写进标签style中
* @param $filename string 保存文件名
* @param $css string css样式内容
*/
function export_pdf_by_mpdf($content, $filename, $css = '')
{
set_time_limit(0); include_once './mpdf/mpdf.php'; //实例化mpdf
$_obj_mpdf = new \mPDF('utf-8', 'A4', '', '宋体', 0, 0, 20, 10); //设置PDF页眉内容 (自定义编辑样式)
$header = '<table width="95%" style="margin:0 auto;border-bottom: 1px solid #4F81BD; vertical-align: middle; font-family:serif; font-size: 9pt; color: #000088;">
<tr><td width="10%"></td><td width="80%" align="center" style="font-size:16px;color:#A0A0A0">页眉</td><td width="10%" style="text-align: right;"></td></tr></table>'; //设置PDF页脚内容 (自定义编辑样式)
$footer = '<table width="100%" style=" vertical-align: bottom; font-family:serif; font-size: 9pt; color: #000088;"><tr style="height:30px"></tr><tr>
<td width="10%"></td><td width="80%" align="center" style="font-size:14px;color:#A0A0A0">页脚</td><td width="10%" style="text-align: left;">
页码:{PAGENO}/{nb}</td></tr></table>'; //添加页眉和页脚到PDF中
$_obj_mpdf->SetHTMLHeader($header);
$_obj_mpdf->SetHTMLFooter($footer); $_obj_mpdf->SetDisplayMode('fullpage');//设置PDF显示方式 $_obj_mpdf->WriteHTML('<pagebreak sheet-size="210mm 297mm" />');//设置PDF的尺寸 A4纸规格尺寸:210mm*297mm !empty($css) && $_obj_mpdf->WriteHTML($css, 1);//设置PDF css样式 $_obj_mpdf->WriteHTML($content);//将$content内容写入PDF $_obj_mpdf->DeletePages(1, 1);//删除PDF第一页(由于设置PDF尺寸导致多出的一页) //输出PDF 直接下载PDF文件
//$_obj_mpdf->Output($filename . '.pdf', true);
//$_obj_mpdf->Output($filename . '.pdf', 'D'); $_obj_mpdf->Output();//输出PDF 浏览器预览文件 可右键保存
exit;
} $html = '<b style="color: red">你看我哪里像好人</b>'; $wordname = 'test-file'; export_pdf_by_mpdf($html, $wordname);