dongxian5735 2013-08-12 19:01
浏览 44
已采纳

创建临时csv下载链接PHP

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);
  • 写回答

1条回答 默认 最新

  • doushi1473 2013-08-12 19:12
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效