Tutorials | PHP & MySQL

Dan Sherwood

Robust CSV export

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);


Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.