win10下始終都是正常的,linux下下載的word文檔始終提示文件損壞之類的
1.使用phpword創建一個word文檔
$phpWord = new \PhpOffice\PhpWord\PhpWord();
//各種操作
if(ob_get_length()) ob_end_clean();//linux加上這一句可能就不會再有文件損壞的問題了,我沒測試,因為發現使用word模版會更方便,如2
$filename = '文件名.docx';
$phpWord->save($file,'Word2007',true);//下載文檔第三個參數為true
2.創建一個word文件,phpword進行加載,替換word中的模版變量就可以,覺得這個很實用,在word中添加變量名,類似:${name}
$docxname = './static/test.docx';
$document = new TemplateProcessor($docxname);
$document->setValues(array('name'=>'姓名'));//word文件中的 ${name}會被替換為姓名
// $document->setImageValue('CompanyLogo', 'path/to/company/logo.png');
$filename = '文件名.docx';
$testPath = './runtime/test_'.uniqid().'.docx';
$document->saveAs($testPath);
// 下載Word文件
if(ob_get_length()) ob_end_clean();//這一句必須,沒有這一句,linux生成的word會提示文件損壞
header('Cache-control: max-age=360');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: '.filesize($testPath));
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Expires: '.gmdate("D, d M Y H:i:s", time() + 360) . ' GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()) . ' GMT');
header('Pragma: public');
ob_start(); //打開緩沖區
echo file_get_contents($testPath);
@unlink($testPath);
ob_end_flush();//輸出全部內容到瀏覽器
exit();
其他操作直接查看phpword官方文檔
$filename