Skip to content

Instantly share code, notes, and snippets.

@graste
Created June 26, 2020 17:10
Show Gist options
  • Save graste/3a597c1ff2a883b25031973dbb0d335f to your computer and use it in GitHub Desktop.
Save graste/3a597c1ff2a883b25031973dbb0d335f to your computer and use it in GitHub Desktop.
handle and test CSV with SplFileObject via in-memory text data - source: https://twitter.com/FredBouchery/status/1276527123172384768
<?php
class MemoryFile extends SplFileObject
{
public function __construct(string $data)
{
parent::__construct('php://memory', 'w+');
$this->fwrite($data);
$this->seek(0);
}
}
$file = new MemoryFile(
<<<FILE
id | name | value | date
1 | foo | 123 | 2020-03-04
2 | bar | asdf | 2020-03-05
FILE
);
$file->setCsvControl('|');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $line) {
var_dump($line);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment