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

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?

图片转代码服务由CSDN问答提供 功能建议

我是PHP的新手,我正在尝试做一个小实验来学习。 \ n

我想创建一行单词,单击它时,将从我在数据库中的表中下载csv文件。

到目前为止,这是我提出的(甚至不是我想做的。但我能够把它变成一个超链接)。< / p>

  echo“&lt; a href = http://www.google.com>点击此处访问网站&lt; / a&gt;”; 
   
 
 

假设我已连接到我的数据库,我将如何连接“点击此处访问网站”以下载csv文件,例如,我的数据库ABC的table1?

我认为必须有一些循环读取table1中的行并将其写入csv文件,对吧?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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);
    ?>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题