Dan Sherwood

Robust CSV export

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
    fpassthru($f);
}

Usage

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

$records = [];
foreach($contacts as $row) {
    $records[] = array(
        $row->firstName, 
        $row->lastName, 
        $row->companyName, 
        $row->challenge1, 
        $row->challenge2, 
        $row->challenge3, 
        $row->created_at
    );
}

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

 

Laravel Modules Book by David Carr

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

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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