Git Product home page Git Product logo

csvparser's Introduction

Csv Parser

Quickly take in and output csv formats.

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads Latest Unstable Version License FOSSA Status

Install

composer require stilliard/csvparser 1.1.7

Example usage:

use CsvParser\Parser;
//
// Simple array to string usage
//
$array = [['id'=>1, 'name'=>'Bob'],['id'=>2, 'name'=>'Bill']];
$parser = new Parser();
$csv = $parser->fromArray($array);
var_dump($parser->toString($csv));

Example stream reading (better memory optimisations)

// stream reading from a CSV file
foreach (Parser::stream(__DIR__ . '/your/path/input.csv') as $row) {
    var_dump($row);
}
// write file
Parser::write($data, __DIR__ . '/your/path/output.csv');
//
// Full power examples:
//

// setup initial parser
$parser = new \CsvParser\Parser(',', '"', "\n");

// change settings after init
// set column delimiter
$parser->fieldDelimiter = ';';
// set text enclosure
$parser->fieldEnclosure = "'";
// set line delimiter
$parser->lineDelimiter = "\n";

// Input (returns instance of \CsvParser\Csv)
$csv = $parser->fromArray([['id'=>1, 'name'=>'Bob'],['id'=>2, 'name'=>'Bill']]);
$csv = $parser->fromString("id,name\n1,Bob\n2,Bill");
$csv = $parser->fromFile('demo.csv');

// get row count
var_dump($csv->getRowCount());

// get the first row as array from the csv
var_dump($csv->first());

// get the column headings / keys
var_dump($csv->getKeys());

// want to force a column sort / index?
$csv->reKey(['id', 'name', 'email']);

// append/prepend rows
$csv->appendRow(['id'=>3, 'name'=>'Ben']);
$csv->prependRow(['id'=>4, 'name'=>'Barry']);

// map function over column
$csv->mapColumn('name', 'trim');
$csv->mapColumn('name', function ($name) {
    return trim($name);
});

// map function over rows
$csv->mapRows(function ($row) {
    $row['codename'] = base64_encode($row['id']);
    return $row;
});

// add a column
$csv->addColumn('codename', 'default value');

// remove a column
$csv->removeColumn('codename');

// filter down rows
$csv->filterRows(function ($row) {
    return $row['id'] != '#'; // remove rows where the id column just has a hash inside
});

// remove row by index
$csv->removeRowByIndex(4);
// or remove row(s) by column value, such as id 22
$csv->removeRow('id', 22);
// or remove row(s) by multiple creiteria, such as when id 22 AND when name is 'some name'
$csv->removeRows(['id'=>22, 'name'=>'some name']);

// Column reordering
$csv->reorderColumn('colname', 0); // move to position 0 (the start)
// or multiple
$csv->reorderColumns(['colname1'=>0, 'colname2'=>4]);

// Row reordering
// to move the row with id of 22 to the start
$csv->reorderRow('id', 22, 0);
// or move id 22 to the start, and id 5 after it
$csv->reorderRows('id', [22 => 0, 5 => 1]);

// Sort rows by a column
$csv->reorderRowsByColumn('id', 'desc');
// or even multiples:
$csv->reorderRowsByColumns(['name', 'id' => 'desc']);

// Output
var_dump($parser->toArray($csv));
var_dump($parser->toString($csv));
var_dump($parser->toFile($csv, 'demo.csv')); // file was created?

// Need to chunk into multiple chunks/files?
$chunks = $parser->toChunks($csv, 1000);
foreach ($chunks as $i => $chunk) {
    $parser->toFile($chunk, "output-{$i}.csv");
}

// Remove duplicates
$csv->removeDuplicates('email');

// Remove blanks
$csv->removeBlanks('email');

License

FOSSA Status

csvparser's People

Contributors

fossabot avatar james-mckinnon avatar scrutinizer-auto-fixer avatar stilliard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

csvparser's Issues

Simple web interface

This could simple be a web interface but with similar commands to the command line interface, but instead with a way to select input type and either upload a file or paste in content. Then a way to select what you'd like to do with the content, e.g. remove duplicates, map something etc. And finally a selection of how you'd like to have the output and if it should be pasted into a text field to be copied somewhere, or given as a download.

Add read/write support for HTML strings

e.g.

<!DOCTYPE html>
<meta charset="utf-8">

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Full name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Test user</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Another test user</td>
        </tr>
    </tbody>
</table>

Simple command line interface

Could be usefull to have a simple way to access basic methods like convertsion and simple maps using stdin and stdout.

E.g.

$ csvparser help
$ echo "id,name\n1,Test user" | csvparser --input-type string --output-type json > out.json
$ csvparser -i "id,name\n1,Test user" --map-row 'name=trim(name)' -o out.json
$ csvparser -i somefile.csv --remove-duplicates email > out.csv

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.