[英]Generate and download CSV file with php and ajax
我有一個php
頁面,它創建一個 CSV 文件,然后瀏覽器會自動下載該文件。 這是一個帶有示例數據的版本 - 效果很好。
<?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);
}
?>
我希望能夠使用ajax
從另一個頁面運行它,以便用戶可以在不離開主頁的情況下生成/下載csv
。 這是我在主頁上使用的JavaScript
。 在我的真實頁面中,我使用的是通過 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);
}
});
});
當我單擊按鈕觸發腳本時,它會運行,但不是保存/下載到csv
而是將整個內容打印到控制台。 有什么辦法可以實現我想要的嗎? 無需實際將文件保存到服務器並重新打開。
我已經通過ajax完成了csv文件下載
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(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);
}
});
});
替換 console.log(result); 帶有文件保存代碼。 在此處檢查JavaScript:創建並保存文件
使用瀏覽器對話框保存文件的最佳方式,使用簡單的代碼。
<a href="#" onclick="window.open('exportCSV.php?year=' + $('input[name="exportYear"]').val())" >Download File</a>
我以前通過創建一個隱藏的 iframe並通過 javascript 將iframe的源設置為一個 php 文件,該文件發送適當的標題和數據,就像您的 exportCSV.php 所做的那樣。
但是,如果你不喜歡這個想法,你可以使用像jQuery File Download或FileSaver.js這樣的庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.