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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据