phpWord报错 new \PhpOffice\PhpWord\TemplateProcessor声明模板时无法创建

Could not create a temporary file with unique name in the specified directory. 

在开发过程中遇到特别头疼的地方,无论我怎么测试都报这个错误。

后来一顿百度,这基本就是没有生成临时文件的权限问题,需要在你生成文件的这个接口中加上

//文件引入  
require '../../Classes/vendor/autoload.php';
use PhpOffice\PhpWord\Settings;

引入文件并使用 PhpOffice\PhpWord\Settings,下面这一步是至关重要的。

// 设置临时文件夹
Settings::setTempDir('../../../FileStorage/exportWord/');

设置完成之后,就可以生成临时文件并创建word文档啦。

以下是所有代码

<?php

include "../header.php";
//文件引入  
require '../../Classes/vendor/autoload.php';
use PhpOffice\PhpWord\Settings;


// 模板的路径
$mobel_path = '../../../FileStorage/importTemplate/template.docx';
// 设置临时文件夹
Settings::setTempDir('../../../FileStorage/exportWord/');
// 声明一个模板对象、读取模板
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($mobel_path);


// 替换模板中的变量,对应word里的 ${title}
// $templateProcessor->setValue('name','小明');
// $templateProcessor->setValue('age','18');

    
$savepath="../../../FileStorage/exportWord/";
$name="小明.docx";
if(empty($filename)) $filename = date('Y-m-d-h-i-s-').$name;  
$full_path = $savepath . $filename;

    // 生成新的word
$templateProcessor->saveAs($full_path);

    if (file_exists($full_path)){
      $tableArray=array(
            "code"=> 200,
            'success'=>true,
            "msg"=> "导出成功",
            'url' =>substr($full_path,8)
     );        
    }else{
          $tableArray=array(
            "code"=> 603,
            'success'=> false,
            "msg"=> "导出失败,请稍后再试",
            'url' =>''
     );    
    }


echo json_encode($tableArray,JSON_UNESCAPED_UNICODE);

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值