Search code examples
phpcsvflysystem

Flysystem/CSV filter a subset of columns


Is it possible to filter a subset of columns of a CSV with Flysystem CSV?

I know that you can use AbstractCsv::addFilter(callable $callback) to add arbitrary filters, but I don't think you would use this to drop a column.


Solution

  • I solved this by getting an array of the column positions that I wanted to filter out. Then, by setting up a new CSV object to write to e.g.

    $new = Writer::createFromFileObject(new \SplTempFileObject);

    With the CSV to read from, I used the each method to iterate through its rows, building a new row using the column indexes built earlier on and inserting into the new CSV. Remember to return true; in the each method or it won't iterate.

    $csv = $csv->newReader();
    $csv->setOffset(1);
    $csv->each(function ($row) use ($new) {
        ... do stuff to alter the row ...
        $new->insertOne($alteredRow)
    });