sharapeco/csv-parser

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

This package is auto-updated.

Last update: 2024-04-15 03:53:08 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',
	...
])
Key Default value Description
internal_encoding 'UTF-8' Encoding of internal data
csv_encoding 'UTF-8' CSV input/output encoding
delimiter ',' Delimiter of columns
quotation '"' Character to quote values includes delimiter, new lines or quotation charater
newline "\n" Character of newline