Create a CSV File for a user in PHP

2018-12-31 16:23发布

I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

20条回答
看风景的人
2楼-- · 2018-12-31 16:41

Here is a full working example using PDO and including column headers:

$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));    
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv'); 
exit();


function download_csv_results($results, $name)
{            
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");    
    fputcsv($outstream, array_keys($results[0]));

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}
查看更多
浮光初槿花落
3楼-- · 2018-12-31 16:41
<?
    // Connect to database
    $result = mysql_query("select id
    from tablename
    where shid=3");
    list($DBshid) = mysql_fetch_row($result);

    /***********************************
    Write date to CSV file
    ***********************************/

    $_file = 'show.csv';
    $_fp = @fopen( $_file, 'wb' );

    $result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");

    while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
    {
        $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
        @fwrite( $_fp, $_csv_data);
    }
    @fclose( $_fp );
?>
查看更多
浅入江南
4楼-- · 2018-12-31 16:41

Here is one I have done before, grabbing data between certain dates. Hope it helps.

<?php
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    ini_set('display_errors',1);
    $private=1;
    error_reporting(E_ALL ^ E_NOTICE);

    mysql_connect("localhost", "user", "pass") or die(mysql_error());
    mysql_select_db("db") or die(mysql_error());

    $start = mysql_real_escape_string($_GET["start"]);
    $end = mysql_real_escape_string($_GET["end"]);

    $query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
    $select_c = mysql_query($query) or die(mysql_error());

    while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
    {
        $result.="{$row['email']},";
        $result.="\n";
        echo $result;
    }
?>
查看更多
梦该遗忘
5楼-- · 2018-12-31 16:43

Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.

$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);

header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
查看更多
零度萤火
6楼-- · 2018-12-31 16:44

In addition to all already said, you might need to add:

header("Content-Transfer-Encoding: UTF-8");

It's very useful when handling files with multiple languages in them, like people's names, or cities.

查看更多
只若初见
7楼-- · 2018-12-31 16:46

How to write in CSV file using PHP script? Actually I was also searching for that too. It is kind of easy task with PHP. fputs(handler, content) - this function works efficiently for me. First you need to open the file in which you need to write content using fopen($CSVFileName, ‘wb’).

$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);

//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
    $line = “”;
    $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
    $line .= “\n”;
    fputs($fp, $line);
}
查看更多
登录 后发表回答