MidnightDesign / sebastianbergmann-csv-parser

Library for type-safe parsing of CSV files

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Latest Stable Version CI Status Type Coverage codecov

sebastian/csv-parser

Library for type-safe parsing of CSV files.

Installation

You can add this library as a local, per-project dependency to your project using Composer:

composer require sebastian/csv-parser

If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:

composer require --dev sebastian/csv-parser

Usage

example.csv

1,2,3,1,0
<?php declare(strict_types=1);
use SebastianBergmann\CsvParser\Parser;
use SebastianBergmann\CsvParser\Schema;
use SebastianBergmann\CsvParser\ColumnDefinition;
use SebastianBergmann\CsvParser\Type;

$schema = Schema::from(
    [
        1 => ColumnDefinition::from('a', Type::integer()),
        2 => ColumnDefinition::from('b', Type::float()),
        3 => ColumnDefinition::from('c', Type::string()),
        4 => ColumnDefinition::from('d', Type::boolean()),
        5 => ColumnDefinition::from('e', Type::boolean()),
    ]
);

$parser = new Parser;

foreach ($parser->parse('example.csv', $schema, false) as $row) {
    var_dump($row);
}

The example above shows how to use a Schema object to configure how a string from a line of comma-separated values is parsed into an array element:

  • 1 refers to the position of the string in the line of comma-separated values
  • 'a' specifies the key for the value in the associative array that is generated for each row
  • Type::integer() specifies the type that should be used to store the value in the associative array that is generated for each row

The following types are available:

  • boolean (Type::boolean(); uses (bool) type cast)
  • integer (Type::integer(); uses (int) type cast)
  • float (Type::float(); uses (float) type cast)
  • string (Type::string())

The Parser::parse() method requires two arguments and accepts an optional third argument:

  • The first argument, $filename, is the path to the CSV file that should be parsed
  • The second argument, $schema, is the Schema object we discussed above
  • The third argument, $ignoreFirstLine (default: true), controls whether the first line of the CSV file should be ignored

Running the example shown above prints the output shown below:

array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  float(2)
  ["c"]=>
  string(1) "3"
  ["d"]=>
  bool(true)
  ["e"]=>
  bool(false)
}

About

Library for type-safe parsing of CSV files

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:PHP 100.0%