由于swoole的服务器中不能出现exit,使用phpWord导出文件的时候直接把导出的二进制文件打印到了调试台了。
$PHPWord = new PhpWord();
$section = $PHPWord->addSection();
$styleTable = array('borderSize' => 6, 'borderColor' => '000', 'cellMargin' => 80);
$styleFirstRow = array('borderBottomSize' => 1, 'borderBottomColor' => '000', 'bgColor' => '000');
// Define cell style arrays
$styleCell = array('valign' => 'center');
$styleCellBTLR = array('valign' => 'center');
// Define font style for first row
$fontStyle = array('bold' => false, 'align' => 'center', 'size' => 14);
// Add table style
$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);
// Add table
$table = $section->addTable('myOwnTableStyle');
$rowHeight = 400;
$cellWidth = 1500;
$cellShortWidth = 1000;
$cellLongWidth = 2700;
// Add row
$table->addRow($rowHeight);
$table->addCell($cellWidth, $styleCell)->addText('班级类型', $fontStyle);
$table->addCell($cellLongWidth, $styleCell)->addText('', $fontStyle);
$table->addCell($cellWidth, $styleCell)->addText('课程时间', $fontStyle);
$table->addCell($cellShortWidth, $styleCell)->addText('', $fontStyle);
$table->addCell($cellWidth, $styleCell)->addText('任课老师', $fontStyle);
$table->addCell($cellShortWidth, $styleCell)->addText('', $fontStyle);
$PHPWord->save('课程活动.doc', 'Word2007', true);
public function save($filename, $format = 'Word2007', $download = false)
{
$mime = array(
'Word2007' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'ODText' => 'application/vnd.oasis.opendocument.text',
'RTF' => 'application/rtf',
'HTML' => 'text/html',
'PDF' => 'application/pdf',
);
$writer = IOFactory::createWriter($this, $format);
if ($download === true) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: ' . $mime[$format]);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$filename = 'php://output'; // Change filename to force download
}
$writer->save($filename);
return true;
}
我用的是phpoffice包来导出;
swoole和导出doc没有直接关系。
出现问题描述的问题是因为输出结果没有返回给请求。
首先,需要分清楚Swoole和传统模式的区别。
传统模式下 echo,var_dump等输出内容都会最终显示在浏览器端,这是因为 fpm或者apache mod_php都会将php输出的内容转发给浏览器。也就是无论你输出什么,你如何输出,我都原封不动的转发。
而Swoole则不同。Swoole相对底层。传统模式相当于动车,你只要坐上去就会出发,路线都是规定好的。而Swoole就是小汽车,去哪里都需要你自己决定,更主要的是,你还需要有驾驶证。
那么Swoole如何输出呢?
可以看到,Swoole接收请求后会出发request事件,该事件有两个参数,一个请求,一个响应。我们获取浏览器段发送的数据从请求中获取,返回浏览器数据需要我们将数据写入响应。
如上代码就可以将Word返回给浏览器了。主要原理就是让word文档生成到缓冲区,也就是生成到内存中,然后生成结束后从内存中读取出来返回给浏览器。另外实际项目中需要注意header使用。浏览器会根据header中Content-Type决定是展示还是下载。