csv/README.md

80 lines
1.3 KiB
Markdown
Raw Normal View History

2015-03-09 18:50:07 +01:00
CSV parser/generator
====================
A simple PHP library to parse and generate CSV files.
2015-03-09 20:47:59 +01:00
## Composer installation
```
$ composer require deblan/csv
```
Or in your composer.json:
```
{
"require": {
2017-03-12 15:20:09 +01:00
"deblan/csv": "~2"
2015-03-09 20:47:59 +01:00
}
}
```
## Usages
2015-03-09 18:40:19 +01:00
2015-03-09 20:29:21 +01:00
### Generator
```php
use Deblan\Csv\Csv;
2015-03-09 20:31:04 +01:00
$csv = new Csv();
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Defines the delimiter (default is ;)
$csv->setDelimiter(";");
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Defines the enclosure (default is ")
$csv->setEnclosure('"');
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Defines the end of line (default is \n)
$csv->setEndOfLine("\n");
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Defines the charset (default is UTF-8)
$csv->setCharset("UTF-8");
// Add a new line at the end
$csv->addData(['Foo', '$1000'));
// Add a new line at the end
$csv->appendData(['Bar', '$600']);
// Add a new line at the beginning
$csv->prependData(['Boo', '$3000']);
// Defines all the datas
$csv->setDatas([[...], [...]]);
// Defines the header
$csv->setHeaders(["Product", "Price"]);
// Rendering
$result = $csv->render();
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Rendering to a file
$result = $csv->render("products.csv");
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Appending to a file
$result = $csv->render("products.csv", FILE_APPEND);
2015-03-09 20:29:21 +01:00
```
### Parser
```php
2015-03-09 20:31:04 +01:00
use Deblan\Csv\CsvParser;
2015-03-09 20:29:21 +01:00
2015-03-09 20:31:04 +01:00
$csv = new CsvParser('products.csv');
$csv->setHasLegend(true);
$csv->parse();
2015-03-09 20:29:21 +01:00
2015-03-09 20:31:04 +01:00
$legend = $csv->getLegend();
$products = $csv->getDatas();
2015-03-09 20:29:21 +01:00
```