Files
webapp/src/Data/CSV.php
T

67 lines
1.8 KiB
PHP

<?php
/*******************************************************************
Module : /Data/CSV.php
Desc. : Class pembuatan file CSV
Created By : Siau Pheng ([email protected]).
Created Date : April 2rd, 2011.
Last Modified : August 21st, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/
declare(strict_types=1);
namespace siaupheng\webapp\Data;
define( DELI_CSV, ";" );
define( CRLF_CSV, "\r\n" );
final class CSV {
private $__avalue = [];
private $__atabel = [];
public function add_field(string $nama, string $func=""): void {
$this->__atabel[] = [ $nama, $func ];
}
public function add_value(): void {
$tmp_arr = func_get_args();
if (is_array($tmp_arr[0])) $tmp_arr = $tmp_arr[0];
$tmp_out = "";
for ($i=0; $i<count($this->__atabel); $i++) {
$tmp_val = $tmp_arr[$i];
if (is_array($this->__atabel[$i][1]) && trim($tmp_val)<>"") {
$tmp_val = $this->__atabel[$i][1][$tmp_val];
} else if (function_exists($this->__atabel[$i][1]) && trim($tmp_val)<>"") {
$tmp_val = call_user_func($this->__atabel[$i][1], $tmp_val);
}
$tmp_out .= DELI_CSV . $tmp_val;
}
$tmp_out = substr($tmp_out, 1);
$this->__avalue[] = $tmp_out;
}
public function download(string $nama_file="export.csv"): void {
$out = ""; $tmp_out = "";
// add header
for ($i=0; $i<count($this->__atabel); $i++) {
$tmp_out .= DELI_CSV . $this->__atabel[$i][0];
}
$out .= substr($tmp_out, 1) . CRLF_CSV;
// add content
for ($i=0; $i<count($this->__avalue); $i++) {
$out .= $this->__avalue[$i] . CRLF_CSV;
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$nama_file."\"");
echo $out;
}
}
?>