douqiao3930 2017-03-10 17:19
浏览 67
已采纳

PHP从数据库导出CSV表

I'm new to PHP and I'm trying to do a small experiment to learn.

I want to create a line of words, that when clicked, will download a csv file from a table I have in my database.

So far, this is what I've come up with (which isn't even near what I want to do. But I was able to make it turn into a hyperlink).

 echo "<a href=http://www.google.com>Click here to visit site</a>";

Assuming I already have a connection to my database, how would I go about connecting "Click here to visit site" to download a csv file, from say, table1 of my database ABC?

I think there will have to be some loop that reads the rows in table1 and writes it into the csv file, right?

  • 写回答

1条回答 默认 最新

  • douan6815 2017-03-10 18:49
    关注

    Create a file separate file having the following code and create a hyperlink in your current file like:

    echo "<a href='http://<your domain name>/test.php'>Click here to visit site</a>";
    
    <?php 
     //test.php
    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    
    // output the column headings
    fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
    
    // fetch the data
    
    $rows = mysqli_query($conn, 'SELECT name, email  FROM users limit 10');
    
    // loop over the rows, outputting them
    while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题