How to read from STDIN instead of a file
tacman opened this issue · 2 comments
tacman commented
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
@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
Thanks. I'll try that.