开发者

How do I put a download button on a site to get a CSV of a table Query?

How do I put a download button on a site to get a CSV of a table Query?

Currently I am using SELECT * INTO OUTFILE to make the CSV file on the server HD and is fine except...

I want to create the CSV like I am now, but I want the "OUTFILE" to be saved on the clients computer when they click Download.

<?php
// Create new file name for file to be created 
$csvfilename = "/dropbox/consolodated-" . date("Y-M-d_H-i-s") . ".csv";


mysql_query ("SELECT * INTO OUTFILE '$csvfilename' FIELDS TERMINATED BY ',' FROM people ");
?>

<H2>Done - Fil开发者_Go百科e created - Now download it from FTP site.</H2>


The solution to this can be that:

  • First you save the csv file on to server.
  • then get it's path
  • and finally create an anchor tag with its path for download eg:

_

 <a href="pathtoyourcsvfile.csv">Download</a>


Here are a couple of similar posts:
Generating CSV file and then forcing the file to download.
PHP code to convert a MySQL query to CSV


Add a POST form at the end which includes a hidden field containing the filename (but NOT the path!) of the file to download. Then have the page it POSTs to read the variable and offer the file for download. Don't forget to enable output buffering and to occasionally flush so that the form is not visible until the query has completed.


Simple, here is a sample snippet:

$csv_filename = "/dropbox/consolodated-" . date("Y-M-d_H-i-s") . ".csv";

Download($csv_filename);

And here is the download function:

function Download($path, $speed = null)
{
    if (is_file($path) === true)
    {
        set_time_limit(0);

        while (ob_get_level() > 0)
        {
            ob_end_clean();
        }

        $size = sprintf('%u', filesize($path));
        $speed = (is_null($speed) === true) ? $size : intval($speed) * 1024;

        header('Expires: 0');
        header('Pragma: public');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . $size);
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Transfer-Encoding: binary');

        for ($i = 0; $i <= $size; $i = $i + $speed)
        {
            echo file_get_contents($path, false, null, $i, $speed);

            flush();
            sleep(1);
        }

        exit();
    }

    return false;
}

Merry Xmas to you too! =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜