Robust CSV export

David Carr

2 min read - 3rd Sep, 2021

csv Export

Table of Contents

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

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.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.