Robust CSV export

Dan Sherwood

Tutorials PHP & MySQL

This article will show you how to export data to a CSV format inside a PHP based project. This export is an improvement on the comparatively basic version which was recommended previously. The main benefits of this method are special characters will not break the CSV export process and instead are treated properly inside the CSV.

There is an optional fourth parameter to specify the delimiter. By default, this will be a comma character.

function csv(array $headerFields, array $records, string $filename, string $delimiter = ',')
    //create a file pointer
    $f = fopen('php://memory', 'w');
    //set column headers
    fputcsv($f, $headerFields, $delimiter);
    foreach($records as $row) {
        //output each row of the data,
        fputcsv($f, array_values($row), $delimiter);

    //move back to beginning of file
    fseek($f, 0);
    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    //output all remaining data on a file pointer


$filename = 'test.csv';
$headerFields = array('First Name', 'Last Name', 'Company', 'Challenge 1', 'Challenge 2', 'Challenge 3', 'Created');

$records = [];
foreach($contacts as $row) {
    $records[] = array(

csv($headerFields, $records, $filename);


Fathom Analytics $10 discount on your first invoice using this link

Help support the blog so that I can continue creating new content!


Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.