CSV Upload/Download
Download CSV File
Let's discuss how to download data as sample.csv
Open the page
function page(Controller $ctl) {
$ctl->show_multi_dialog("download_csv", "csv.tpl", "Download CSV File", 800, true, true);
}
View (csv.tpl)
class: this must be "download-link"
data-filename: download file name
<p>CSV Download</p>
<button class="download-link" data-class="mycsv" data-function="download" data-filename="sample.csv">Download</button>
Class
function download(Controller $ctl) {
//data array
$csv_data = [
['id', 'name', 'address'],
[1, 'name one', 'address one'],
[2, 'name two', 'address two'],
[3, 'name three', 'address three']
];
//response csv file
//sjis-win is the Japanese character encoder
foreach ($csv_data as $row) {
$ctl->res_csv($row, 'sjis-win');
}
}
Upload and Read CSV file
View (csv.tpl)
<p>CSV Upload</p>
<form id="csvform">
<input type="file" name="csvfile">
</form>
<button class="ajax-link" data-class="mycsv" data-function="upload" data-form="csvform">Upload</button>
{* separator *}
<div style="clear:both; border-bottom:1px #ccc solid; width:100%; padding-top;20px;"></div>
{* CSV output will be print here *}
<div id="csvresult"></div>
function upload(Controller $ctl) {
//save uploaded file as csvdata.csv
$ctl->save_posted_file('csvfile', 'csvdata.csv');
//get saved file path
$filepath = $ctl->get_saved_filepath('csvdata.csv');
//open saved file
$fp = fopen($filepath, 'r');
//set encoding for japanese
stream_filter_register('convert.mbstring.*', 'Stream_Filter_Mbstring');
$filtername = 'convert.mbstring.encoding.SJIS-win:UTF-8';
stream_filter_append($fp, $filtername, STREAM_FILTER_READ);
//read each line as csv
$txt = "";
while ($row = fgetcsv($fp)) {
//$row has column data
$txt .= print_r($row, true) . "<br/>";
}
//close file
fclose($fp);
//response csv data to the view
$ctl->reload_area('#csvresult', $txt);
}