PHP code example of phillipsdata / csv

1. Go to this page and download the library: Download phillipsdata/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/ */

    

phillipsdata / csv example snippets




use PhillipsData\Csv\Reader;

// Set the input for the reader
$reader = Reader::input(new SplFileObject('php://stdin'));

$lines = [];
// Fetch the result for each line read
foreach ($reader->fetch() as $line) {
    $lines[] = $line;
}




use PhillipsData\Csv\Writer;

$writer = Writer::output(new SplFileObject('/path/to/file.csv'));

$data = [
    ['colA', 'colB'],
    ['A1', 'B1'],
    ['A2', 'B2']
];

// Write all rows (works great with Iterators)
$writer->write($data);

// Or, write a single row at a time
foreach ($data as $row) {
    $writer->writeRow($row);
}




use PhillipsData\Csv\Factory;

// returns \PhillipsData\Csv\Writer
$writer = Factory::writer('path/to/file', ',', '"', '\\');

// returns \PhillipsData\Csv\Reader
$reader = Factory::reader('path/to/file', ',', '"', '\\');



// The formatter is called for each line parsed
$reader->format(function ($line, $key, $iterator) {
    return [
        'first_name' => $line['First Name'],
        'last_name' => $line['Last Name'],
        'email' => strtolower($line['Email']),
        'date' => date('c', strtotime($line['Date']))
    ];
});

foreach ($reader->fetch() as $line) {
    // $line now contains 'first_name', 'last_name', 'email', and 'date'.
}



// The formatter is called for each line parsed
$reader->filter(function ($line, $key, $iterator) {
    return $line['Last Name'] === 'Smith';
});

foreach ($reader->fetch() as $line) {
    // $line only contains records where $line['Last Name'] === 'Smith'
}