Last Updated: February 25, 2016
·
3.135K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside