如何使用Codeigniter框架将数组保存为文件并将其下载而不先保存在服务器上?
我有两个按钮:
<button id='csv' class='btn-success btn-sm pull-right'>Pobierz CSV</button>
<button id='xls' class='btn-success btn-sm pull-right'>Pobierz XLS</button>
然后使用AJAX:
$(document).ready(function () {
$('#csv').click(function () {
$.ajax({
url: window.location + "crawler/metoda",
type: "POST",
data: {
wartosc: 'csv'
}
})
})
$('#xls').click(function () {
$.ajax({
url: window.location + "crawler/metoda",
type: "POST",
data: {
wartosc: 'xls'
}
})
})
});
发送var wartosc切换到metoda方法:
switch($_POST["wartosc"])
{
case "xls" :
//code generate .xls file
exit();
case "csv" :
//and here generate .csv
exit();
}
我尝试了几种解决方案,但它们仅适用于纯php,例如:
<?php
$data = array(
'0' => array('Key1' => 'value1', 'Key2' => 'value2', 'Key3' => 'value3', 'Key4' => 'value4'),
'1' => array('Key1' => 'value1', 'Key2' => 'value2', 'Key3' => 'value3', 'Key4' => 'value4'),
'2' => array('Key1' => 'value1', 'Key2' => 'value2', 'Key3' => 'value3', 'Key4' => 'value4'),
'3' => array('Key1' => 'value1', 'Key2' => 'value2', 'Key3' => 'value3', 'Key4' => 'value4')
);
$csvName = 'temp.csv';
$fp = fopen($csvName, 'w');
foreach ($data as $line) {
fputcsv($fp, $line);
}
fclose($fp);
$csvData = file_get_contents($csvName);
header('Content-Type: application/vnd.ms-excel');
header('Content-Length: ' . strlen($csvData));
echo $csvData;
exit;