https://github.com/xp-framework/csv
CSV File handling for the XP Framework
https://github.com/xp-framework/csv
csv php stream xp-framework
Last synced: 7 months ago
JSON representation
CSV File handling for the XP Framework
- Host: GitHub
- URL: https://github.com/xp-framework/csv
- Owner: xp-framework
- Created: 2013-11-11T09:52:51.000Z (about 12 years ago)
- Default Branch: master
- Last Pushed: 2024-03-24T11:46:12.000Z (almost 2 years ago)
- Last Synced: 2025-05-30T13:09:11.908Z (7 months ago)
- Topics: csv, php, stream, xp-framework
- Language: PHP
- Size: 3.22 MB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: ChangeLog.md
Awesome Lists containing this project
README
CSV File handling for the XP Framework
========================================================================
[](https://github.com/xp-framework/csv/actions)
[](https://github.com/xp-framework/core)
[](https://github.com/xp-framework/core/blob/master/LICENCE.md)
[](http://php.net/)
[](http://php.net/)
[](https://packagist.org/packages/xp-framework/csv)
Contains the XP Framework's CSV API
Reading
-------
CSV data can be read off any input stream, reader or channel:
```php
use util\cmd\Console;
use text\csv\CsvListReader;
use io\streams\FileInputStream;
$csv= new CsvListReader(new FileInputStream('in.csv'));
Console::writeLine($csv->getHeaders());
while ($record= $csv->read()) {
Console::writeLine('- ', $record);
}
$csv->close();
```
Writing
-------
CSV data can be written to any output stream, writer or channel:
```php
use util\cmd\Console;
use text\csv\CsvListWriter;
use io\streams\FileOutputStream;
$csv= new CsvListWriter(new FileOutputStream('out.csv'));
$csv->setHeader(['name', 'city', 'zip']);
$csv->write(['Timm', 'Karlsruhe', 76137]);
$csv->write(['Alex', 'Karlsruhe', 76131]);
$csv->close();
```
Character set conversion
------------------------
Character set decoding is accomplished by passing a TextReader or TextWriter instance with a given character set:
```php
use text\csv\{CsvListReader, CsvListWriter};
use io\streams\{FileInputStream, FileOutputStream, TextReader, TextWriter};
// Read from in.csv, which is in cp1252
$in= new CsvListReader(new TextReader(new FileInputStream('in.csv'), 'cp1252'));
// Write to out.csv, converting everything to cp1252
$out= new CsvListWriter(new TextWriter(new FileOutputStream('out.csv'), 'cp1252'));
```
Format
------
CSV files usually use the semi-colon to separate values. Depending on the file we're parsing, this might be a different character. Both readers and writers accept an optional second parameter with which the format can be changed.
```php
use text\csv\{CsvFormat, CsvListReader, CsvListWriter};
$format= (new CsvFormat())->withDelimiter(',');
$format= CsvFormat::$COMMAS; // Short-hand for the above
$writer= new CsvListWriter(..., $format);
$reader= new CsvListReader(..., $format);
```