Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a CSV File for a user in PHP

People also ask

How do I import and export CSV using PHP and MySQL?

php'); $csv_file = $_FILES['csv_file']['tmp_name']; if (is_file($csv_file)) { $input = fopen($csv_file, 'a+'); $row = fgetcsv($input, 1024, ','); // here you got the header while ($row = fgetcsv($input, 1024, ',')) { // insert into the database $date = date('Y-m-d H:i:s'); $sql = 'INSERT INTO users(first_name,last_name ...

What is Fputcsv?

fputcsv(file, fields, separator, enclosure, escape)

How do I store form data in a CSV file?

For make this type of system here we have use PHP script. We have use some PHP in build function like fopen() for open file for write operation, file() function for get file data in array format for count number of rows in file and fputcsv() function for write form data in csv file.


header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

php://output
fputcsv


Try:

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

echo "record1,record2,record3\n";
die;

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

Here is an improved version of the function from php.net that @Andrew posted.

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

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

    $outstream = fopen("php://output", "wb");

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

    fclose($outstream);
}

It is really easy to use and works great with MySQL(i)/PDO result sets.

download_csv_results($results, 'your_name_here.csv');

Remember to exit() after calling this if you are done with the page.


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.


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