csv/README.md

99 lines
1.7 KiB
Markdown
Raw Normal View History

2015-03-09 18:50:07 +01:00
CSV parser/generator
====================
2018-06-06 18:59:00 +02:00
<a href="https://phpci.gitnet.fr/build-status/view/2">![](https://phpci.gitnet.fr/build-status/image/2?branch=master&label=PHPCensor&style=flat-square)</a>
2017-03-12 17:57:30 +01:00
2015-03-09 18:50:07 +01:00
A simple PHP library to parse and generate CSV files.
2015-03-09 20:47:59 +01:00
## Composer installation
```
2018-06-06 15:51:31 +02:00
$ composer require deblan/csv "~2"
2015-03-09 20:47:59 +01:00
```
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
2017-03-12 17:57:30 +01:00
$csv->setHeaders(['Product', 'Price']);
2017-03-12 15:20:09 +01:00
// Rendering
$result = $csv->render();
2015-03-09 20:29:21 +01:00
2017-03-12 15:20:09 +01:00
// Rendering to a file
2017-03-12 17:57:30 +01:00
$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
2017-03-12 17:57:30 +01:00
$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
2017-03-12 17:57:30 +01:00
$csv = new CsvParser();
// Defines the delimiter (default is ;)
$csv->setDelimiter(";");
// Defines the enclosure (default is ")
$csv->setEnclosure('"');
// Defines the end of line (default is \n)
$csv->setEndOfLine("\n");
// Headers?
$csv->setHasHeaders(true);
// Parse a file
$csv->parseFile('products.csv');
// Parse a string
$csv->parseString($myString);
2015-03-09 20:29:21 +01:00
2017-03-12 17:57:30 +01:00
// Headers and datas
$headers = $csv->getHeaders();
2015-03-09 20:31:04 +01:00
$products = $csv->getDatas();
2015-03-09 20:29:21 +01:00
```