我正在使用PHPspreadsheet
在xampp上创建xlsx文件。我想在wordpress中运行cron作业,它将自动导出一些订单并将xlsx文件保存在xampp服务器上。我已经成功地使用$writer->save('php:\output');
导出了一个文件,但这只是询问用户在哪里下载文件。
我希望cron作业将在不询问用户的情况下保存文件。即wp内容/导出/$filename
标题:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="file.xls"');
header('Cache-Control: max-age=0');
PHP:
$objWriter = new Xlsx($objX);
ob_start();
$objWriter->save('php://output');
$xlsData = ob_get_contents();
ob_end_clean();
//returning response to javascript
$response = array(
'file_name' =>'s.xlsx',
'op' => 'ok',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData),
);
die(json_encode($response));
Javascript
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
form_data :detail_info,
action: 'frontend_action_without_file' // this is going to be used inside wordpress functions.php
},
error: function(error) {
},
success: function(response) {
//console.log("Insert Success" + response.file);
}
}).done(function(data){
var $a = jQuery("<a>");
$a.attr("href",data.file);
jQuery("body").append($a);
$a.attr("download",data.file_name);
$a[0].click();
});
});
您需要创建另一个页面,并使用一个函数从url下载文件(在这种情况下,您的页面生成xlsx(,示例如下。
private function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen ($url, 'rb');
if ($file) {
$newf = fopen ($newfname, 'wb');
if ($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
downloadFile('https://yoururl.com/generateXlsx.php', 'xlsx/file.xlsx');
之后只执行这个shell
* 10 * * * php -f /home/dev/cronjobs/downloadfile.php
这个命令每天上午10点执行您的代码/home/dev/cronjobs/downloadfile.php
是文件路径。
ps。您可以使用https://crontab-generator.org/生成你的外壳的