thephpleague / csv

CSV data manipulation made easy in PHP
https://csv.thephpleague.com
MIT License
3.34k stars 336 forks source link

How to read from STDIN instead of a file #503

Closed tacman closed 1 year ago

tacman commented 1 year ago
Q A
Version 9.0

Question

All of the examples at https://csv.thephpleague.com/9.0/reader/ use createFromFile or createFromString. I want to read from the input stream (so I can pipe csv data to a script), but I'm not sure how to instantiate the readFromStream.

cat data.csv | myscript.php
        $reader = \League\Csv\Reader::createFromStream($stdin = fopen('php://stdin', 'r'));
        foreach ($reader->getRecords() as $record) {
            // ...
        }

In UnavailableFeature.php line 40:

stream does not support seeking.

Can you provide an example on that page? I'm suspect there's a way and it's just a matter of creating the stream from the STDIN.

Thanks.

nyamsprod commented 1 year ago

@tacman currently this is not possible as the resource is processed via an internal class Stream which requires the stream to be seekable. a workaround would be to use stream_copy_to_stream as shown below:

<?php

use League\Csv\Reader;

$tmp = tmpfile();
stream_copy_to_stream(STDIN, $tmp);

$reader = Reader::createFromStream($tmp);
foreach ($reader as $record) {
    // ...
}
?>
tacman commented 1 year ago

Thanks. I'll try that.