【发布时间】:2018-07-27 07:02:35
【问题描述】:
我有一个生成和下载 CSV 文件的 PHP 脚本。以下是该脚本的代码:
<?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,而是回显数组作为响应。任何帮助都会得到帮助。
【问题讨论】:
-
还在代码末尾添加
exit;或die; -
@Sudharshan Nair,已经完成了。但不工作。