[英]Generate and download CSV file with php and ajax
I have a php
page that creates a CSV file that is then downloaded by the browser automatically.我有一个
php
页面,它创建一个 CSV 文件,然后浏览器会自动下载该文件。 Here is a version with sample data - it works great.这是一个带有示例数据的版本 - 效果很好。
<?php
$cars = array(
array("Volvo",22,18),
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);
}
?>
I would like to be able to run this from another page using ajax
so that a user can generate/download a csv
without leaving the main page.我希望能够使用
ajax
从另一个页面运行它,以便用户可以在不离开主页的情况下生成/下载csv
。 This is the JavaScript
I am using on the main page.这是我在主页上使用的
JavaScript
。 In my real page I am using the data coming via ajax.在我的真实页面中,我使用的是通过 ajax 传入的数据。
$('button[name="exportCSVButton"]').on('click', function() {
console.log('click');
$.ajax({
url: 'exportCSV.php',
type: 'post',
dataType: 'html',
data: {
Year: $('input[name="exportYear"]').val()
},
success: function(data) {
var result = data
console.log(result);
}
});
});
When I click the button to trigger the script, it runs, but instead of saving/download to csv
it prints the entire thing to console.当我单击按钮触发脚本时,它会运行,但不是保存/下载到
csv
而是将整个内容打印到控制台。 Is there any way to accomplish what I want?有什么办法可以实现我想要的吗? Without actually saving the file to the server and reopening.
无需实际将文件保存到服务器并重新打开。
I have done csv file download via ajax我已经通过ajax完成了csv文件下载
PHP Code
PHP代码
<?php
function outputCsv( $assocDataArray ) {
if ( !empty( $assocDataArray ) ):
$fp = fopen( 'php://output', 'w' );
fputcsv( $fp, array_keys( reset($assocDataArray) ) );
foreach ( $assocDataArray AS $values ):
fputcsv( $fp, $values );
endforeach;
fclose( $fp );
endif;
exit();
}
function generateCsv(){
$res_prods = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}products` ", OBJECT );
$products= [];
foreach ($res_prods as $key => $product) :
$product_id = $product->ID;
$products[$product_id]['product_id'] = $product_id;
$products[$product_id]['name'] = $product->name;
endforeach;
return outputCsv( $products);
}
jQuery AJAX
jQuery AJAX
jQuery(document).on( 'click', '.btn_generate_product', function(e) {
var product_id = jQuery(this).data('product_id');
jQuery.ajax({
url : "ajaxurl",
type: 'POST',
data: { product_id },
success: function(data){
/*
* Make CSV downloadable
*/
var downloadLink = document.createElement("a");
var fileData = ['\ufeff'+data];
var blobObject = new Blob(fileData,{
type: "text/csv;charset=utf-8;"
});
var url = URL.createObjectURL(blobObject);
downloadLink.href = url;
downloadLink.download = "products.csv";
/*
* Actually download CSV
*/
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
});
});
Replace console.log(result);替换 console.log(result); with file save code.
带有文件保存代码。 check here JavaScript: Create and save file
在此处检查JavaScript:创建并保存文件
The best way to save file with browser dialog box, use simple code.使用浏览器对话框保存文件的最佳方式,使用简单的代码。
<a href="#" onclick="window.open('exportCSV.php?year=' + $('input[name="exportYear"]').val())" >Download File</a>
I did it time ago by creating a hidden iframe and via javascript the source of the iframe was set to a php file which sent the appropriate headers and data as your exportCSV.php does.我以前通过创建一个隐藏的 iframe并通过 javascript 将iframe的源设置为一个 php 文件,该文件发送适当的标题和数据,就像您的 exportCSV.php 所做的那样。
But, if you don't like this idea, you could use a library like jQuery File Download or FileSaver.js但是,如果你不喜欢这个想法,你可以使用像jQuery File Download或FileSaver.js这样的库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.