PHP's fputcsv function is very useful for creating CSV files, but by default will write out to a file. There are a couple of tricks to be able to keep it all in memory or instead write the CSV data out directly to the web browser without having to write your own custom functions.
Array to CSV function using fputcsv
This function takes an array and returns the correctly formatted CSV data as a string using an in-memory buffer. It takes the same parameters as the fputcsv function, passing them through to it, so it can be used in the same way as fputcsv.
Note that you can substitute php://temp for php://memory. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB).
Here's an example:
And the output:
Writing the array straight out to the browser
Instead of buffering the CSV data in memory, you can write it directly out to the data by using php://output instead of php://temp or php://memory:
Note that if you are writing CSV data directly out to the browser, you'll want to set the appropriate headers too.
0 comments:
Post a Comment