CodeIgniter 4: ekspor data ke format CSV

Untuk ekspor data dari database ke format CSV tidak memerlukan library, bisa langsung menggunakan fungsi-fungsi yang ada di PHP

// app\Controllers\Laporan.php

public function csv()
{
    // Load data dari model
    $siswa = $this->siswa->findAll();

    // Nama file untuk diunduh
    $filename = 'data_siswa.csv';

    // Set header untuk file CSV
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0");

    // Membuka output stream
    $file = fopen('php://output', 'w');

    // Tulis header kolom ke file CSV
    fputcsv($file, ['Nama Siswa', 'Nilai']);

    // Tulis data siswa ke file CSV
    foreach ($siswa as $row) {
        fputcsv($file, [
            $row['nama_siswa'],
            $row['nilai'],
        ]);
    }

    // Tutup stream file
    fclose($file);
    exit();
}
// app\Config\Routes.php

$routes->get('laporan/csv', 'Laporan::csv');
// app\Views\laporan\index.php

<a href="<?= base_url('laporan/csv'); ?>" target='blank' class='btn btn-primary'>Ekspor CSV</a>

Posting Komentar