我有一个PHP脚本,可以生成和下载CSV文件。以下是该脚本的代码:
<?php
$cars = array(
array("Volvo",22,1888),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));
//Loop through the array and add to the csv
foreach ($cars as $row) {
fputcsv($output, $row);
}
exit;
?>
当我直接访问该脚本时,它可以正常工作,但是我的目标是在WordPress AJAX调用中使用此脚本,我使用WordPress AJAX API创建了AJAX,如下所示:
add_action( 'wp_ajax_export_timeline', 'export_timeline' );
然后在回调函数export_timeline
中编写相同的PHP代码(上面粘贴的),但是不是生成CSV并针对AJAX调用下载,而是返回打印数组。调用中的AJAX没有错误,我已经通过回显其他字符串进行了测试,其响应良好。
但是在上面提到的脚本的情况下,我认为PHP标头在回调函数中不起作用,因为它不是生成和下载CSV,而是在响应时回显数组。任何帮助都可以申请。
答案 0 :(得分:0)
尝试直接调用url,而不进行ajax调用,那么它应该可以工作。
答案 1 :(得分:0)
尝试如下修改标题
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=csvfile.csv" );
header("Content-Transfer-Encoding: binary");
答案 2 :(得分:0)
据我所知,PHP标头不适用于AJAX调用:
您可以做的是在php代码中创建csv数据,并将其作为对回调的响应。
您的php代码必须返回一个json作为
echo json_encode(['data' => $data, 'status' => 'success' ]);
$data
变量必须具有有效的CSV格式数据。
在您的JavaScript中,您可以使用以下内容进行CSV下载:
function download_csv(){
var make_download = (function () {
var $a = $('<a>', {
'class': 'csv-downloader',
'style': 'display: none'
});
$('body').find('.csv-downloader').remove();
$('body').append($a);
return function (data, fileName) {
const blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
$a[0].href = url;
$a[0].download = fileName;
$a[0].click();
window.URL.revokeObjectURL(url);
};
}());
$.when($.ajax({
dataType: 'json',
method: 'POST',
url: URL, // url here
})).then((response) => {
if (response.status == 'success') {
make_download(response.data, `my-file.csv`);
}
})
}