zoukankan      html  css  js  c++  java
  • phpword 导出word,文件已损坏问题

    win10下始终都是正常的,linux下下载的word文档始终提示文件损坏之类的

    1.使用phpword创建一个word文档

    $phpWord = new PhpOfficePhpWordPhpWord();
    //各种操作
    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);//php://output
    // 下载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官方文档

    php://output
  • 相关阅读:
    axis
    LRU
    apk 反编译
    android 设置 button 不同状态的图片
    resin
    scrum 项目管理
    android 国外广告平台
    JNI
    java 通信
    google网站分析
  • 原文地址:https://www.cnblogs.com/benlightning/p/11905856.html
Copyright © 2011-2022 走看看