Search code examples
phplaravellaravel-5.3flysystem

How can I use a resource to write line by line but still use Laravel's built in Storage?


I want to use Storage::put to write a file. The file is potentially very large (>100MB), so I want to utilise a stream so I don't blindly place everything into memory.

I'm going to be making multiple API requests, and then looping through their results, so the data I'll be getting back isn't an issue, it'll be limited to sensible amounts.

According to the documentation, I need to use:

Storage::put('file.xml', $resource);

But what would $resource be here?

Traditionally when writing files using PHP I have done it with a combination of fopen, fwrite and fclose in order to write 'line by line'. I'm building the file up by looping through various Collections and utlising various APIs as I go, so $resource is NOT a file pointer or file reference as is talked about elsewhere in the documentation.

So, how can I write line by line using a stream and Laravel's Storage?


Solution

  • Storage::put('file.xml', $resource);
    

    But what would $resource be here?

    $resource is your data that you prepare to write to disk by code.

    If you want to write the file with a loop you must use the Storage::append($file_name, $data); as wrote before by ljubadr

    I wrote $data but you can use any name you want for a variable inside a loop.