Reputation: 866
I have the following PHP code to take a multidimensional array and output it to a file in my php page's directory. This works great.
I'm looking for a solution to create a temporary download link on the page that this code resides on, so that the user can choose to click the link or not, and the file is deleted when the page is closed, or some fixed time.
I haven't found a good example of how to implement this on a temporary basis. using tmpfile() seems to not allow me to create a .csv file (it's just .tmp), and I'm not even sure if the file would exist after the page loads (long enough for the user to download).
Also, a lot of examples assume that the information is already coming in via $_POST. The page that my code resides on is already the target from a previous POST action. I'm not sure how I'd get the data from the $results array over to a theoretical download.php file.
I'm at a bit of a crossroads, and my specific question doesn't seem to duplicate anything I've found on SO today. Ideas? (NOTE: The array of blanks just acts as a separator for each set of values)
$fp = fopen('file.csv','w');
foreach ($results as $arrays){
foreach ($arrays as $fields) {
fputcsv($fp, $fields);
}
$blanks = array(' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ');
fputcsv($fp, $blanks);
}
fclose($fp);
Upvotes: 0
Views: 1873
Reputation: 4350
The problem, it seems, is that you are creating a temp file when you should be creating an actual file. Temp files are meant to be created and destroyed at runtime. If you are trying to create a file that actually lives on the server for a brief time you need to use file_put_contents
. You would then have a file on your server with the contents of the CSV. You could create a function that creates the file and returns the location that you could then pass to your HTML page. You would then need to create a cleanup routine to occasionally empty the directory if files become outdated.
I hope this gets you pointed in the right direction!
Upvotes: 1