PHP code example of xp-framework / csv

1. Go to this page and download the library: Download xp-framework/csv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xp-framework / csv example snippets


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();

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();

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'));

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);