sharapeco/csv-parser

Simple CSV Parser

v1.0.1 2023-06-15 02:08 UTC

This package is auto-updated.

Last update: 2024-12-15 05:07:24 UTC


README

CSVParser can:

  • Parse CSV from string
  • Output indexed arrays or associative arrays
  • Output CSV from associative arrays

Usage

Basic:

$csv = 'aaa,bbb,ccc
ddd,eee,fff
ggg,hhh,iii';

$parser = new \sharapeco\CSVParser\CSVParser();
$parser->parse($csv);

// => [
//   ['aaa', 'bbb', 'ccc'],
//   ['ddd', 'eee', 'fff'],
//   ['ggg', 'hhh', 'iii'],
// ]

Associate with key:

$csv = 'aaa,bbb,ccc
ddd,eee,fff
ggg,hhh,iii';
$keys = ['foo', 'bar', 'baz'];

$parser = new \sharapeco\CSVParser\CSVParser();
$parser->parse($csv, $keys);

// => [
//   ['foo' => 'aaa', 'bar' => 'bbb', 'baz' => 'ccc'],
//   ['foo' => 'ddd', 'bar' => 'eee', 'baz' => 'fff'],
//   ['foo' => 'ggg', 'bar' => 'hhh', 'baz' => 'iii'],
// ]

Render CSV:

$rows = [
    ['foo' => 'aaa', 'bar' => 'bbb', 'baz' => 'ccc'],
    ['foo' => 'ddd', 'bar' => 'eee', 'baz' => 'fff'],
    ['foo' => 'ggg', 'bar' => 'hhh', 'baz' => 'iii'],
];
$header = ['foo', 'bar', 'baz'];

$parser = new \sharapeco\CSVParser\CSVParser();
$parser->render($rows, $header);

Settings

$parser = new CSVParser([
    'csv_encoding' => 'sjis-win',
	...
])