Contains the XP Framework's CSV API
CSV data can be read off any input stream, reader or channel:
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();
CSV data can be written to any output stream, writer or channel:
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 decoding is accomplished by passing a TextReader or TextWriter instance with a given character set:
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'));
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.
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);