Last Updated: February 25, 2016
·
2.645K
· Andrew Stilliard

Multidimensional array to CSV in PHP

First install this lib with composer:

composer require stilliard/csvparser dev-master

Make sure its autoloaded in, if not already:

require_once 'vendor/autoload.php';

And then to test it out:

// create a test array
$array = [
    ['id'=>1, 'name'=>'Bob'],
    ['id'=>2, 'name'=>'Bill']
];

// create a parser to handle the input/output of the csv
$parser = new \CsvParser\Parser();

// use the parser to convert the array to a csv object
$csv = $parser->fromArray($array);

// use the parser to convert the csv object to a string
echo $parser->toString($csv);

Checkout more information here:
https://github.com/stilliard/CsvParser