sharapeco / php-csv-parser

Simple CSV Parser for PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple CSV Parser for PHP

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

About

Simple CSV Parser for PHP

License:MIT License


Languages

Language:PHP 100.0%