Loading...

Export to CSV

David Carr

1 min read - 21st Dec, 2018

Today I've released a new PHP package for exporting array data to a CSV file. Often data needs exporting from a database into CSV files. 

To install the package import it with composer:

composer require daveismyname/exportcsv

Then to use it import the namespace

use Daveismyname\ExportCsv\ExportCsv;

To export the data the following is required

//set filename
$filename = 'test.csv';

//set column names
$headerFields = array('First Name', 'Last Name', 'Company', 'Created');

//create array
$records = [];

//loop through data and add to array
foreach($contacts as $row) {
    $records[] = array(
        $row->firstName, 
        $row->lastName, 
        $row->companyName, 
        $row->created_at
    );
}

//send params to csv 
new csv($records, $filename, $headerFields);

More details can be found at https://github.com/daveismyname/exportcsv

0 comments
Add a comment