Create a CSV File for a user in PHP

前端 未结 19 1876
故里飘歌
故里飘歌 2020-11-22 11:52

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.

<
相关标签:
19条回答
  • 2020-11-22 12:12

    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);
    
    0 讨论(0)
  • 2020-11-22 12:13

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 12:14

    First make data as a String with comma as the delimiter (separated with ","). Something like this

    $CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine
    
    $rand = rand(1,50); //Make a random int number between 1 to 50.
    $file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                         //side it is recommended that the file name be different.
    
    file_put_contents($file,$CSV_string);
    
    /* Or try this code if $CSV_string is an array
        fh =fopen($file, 'w');
        fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
        fclose($fh);
    */
    
    0 讨论(0)
  • 2020-11-22 12:14

    Simple method -

    $data = array (
        'aaa,bbb,ccc,ffffdd',
        '123,456,789',
        '"aaa","bbb"');
    
    $fp = fopen('data.csv', 'wb');
    foreach($data as $line){
        $val = explode(",",$line);
        fputcsv($fp, $val);
    }
    fclose($fp);
    

    So each line of the $data array will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.

    0 讨论(0)
  • 2020-11-22 12:15

    The thread is a little old, I know, but for future reference and for noobs as myself:

    Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:

    <a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>
    

    my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:

    User_John_Doe_10_Dec_11.csv
    
    0 讨论(0)
  • 2020-11-22 12:16

    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.

    0 讨论(0)
提交回复
热议问题