bovigo / vfsStream

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.
BSD 3-Clause "New" or "Revised" License
1.42k stars 102 forks source link

Create CSV file in the custom path using VFS #266

Open jmdeepak007git opened 3 years ago

jmdeepak007git commented 3 years ago

HI Guys,

I have a symfony php command where the parameter expects to send a csv file path. I would like to create a csv in a custom path using VFSStream. How is it possible to achieve this please ?

I can see when I create a csv file in the root directory. I see vfs embed path like this vfs:/root/foo.csv. Instead of the above path, I would like to create foo.csv in a custom local directory.

Thanks alot.

allejo commented 3 years ago

I would like to create foo.csv in a custom local directory.

Are you looking for file_put_contents? Just give it a local path instead of a VFS path.

jmdeepak007git commented 3 years ago

But I would like to use VFS file system for storing data in a virtual file.

bizurkur commented 3 years ago

If you mean "custom local directory" INSIDE vfs, then:

$root = vfsStream::setup();
$myCustomDir = $root->url() . '/some/custom/path';
// vfs://root/some/custom/path
mkdir($myCustomDir, 0777, true);

$myCsvFile = $myCustomDir . '/some.csv';
// vfs://root/some/custom/path/some.csv
file_put_contents($myCsvFile, "a,b,c\r\n1,2,3\r\n");

echo file_get_contents($myCsvFile);

If you don't want root as the first folder:

$root = vfsStream::setup('my_folder'); // <-- give a custom name for "root"
echo $root->url();
// vfs://my_folder

However, once that php process exits that file no longer exists. If you're trying to run a symfony command like bin/console some:command vfs://path/to/some.csv it's not going to work.

If you're creating the file in-memory within the command, you don't need vfs for that.

// write CSV to memory
$fh = fopen('php://temp', 'w+');
fputcsv($fh, ['a', 'b', 'c']);
fputcsv($fh, ['1', '2', '3']);

// rewind to start of file
rewind($fh);

// read the file and do whatever you want with the data
while (($data = fgetcsv($fh, 1000, ",")) !== false) {
    var_dump($data);
}
fclose($fh);