Создаем csv файл php

Create a CSV File for a user in PHP

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 Answers 20

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") )); 

More people need to see this and vote it up. This is easily the best answer on this page. PHP already has built-in functions for formatting CSV content. Everyone should use them. Great answer, @Andrey 🙂

Nice, but the outputCSV function is needlessly complicated. You can just foreach over $array , sending its values straight into fputcsv . No need for that __outputCSV and the array_walk 🙂 foreach($data as $vals)

I’m having some issues with French characters in the array because I eventually need the .csv to be open in Excel. It chokes on the accented characters. Things like «Prévalence»,»age 1″,»city 1″ Any ideas? Messing with UTF-8 hasn’t helped thus far.

Don’t know why but its not working in my case. I’m fetching rows from database as while($row as mysql_fetch_array($res)) <$data[] = $row;>. Also, I’m not getting what is php://output used for

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; 

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; > 

note the rules for CSVs are important. To ensure good display, put doublequotes around your fields, and don’t forget to replace double-quotes inside fields to double double-quotes: `echo ‘»‘.str_replace(‘»‘,'»»‘,$record1).'»,»‘.str_replace.

Just to clarify, the correct HTTP Content-Type header for CSV is text/csv, not application/csv. I doubt any modern browser will care either way, but since there are standards we might as well use them.

@Oleg Barshay: OMG, that RFC is a master piece: «If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.». ANOTHER DOUBLE-QUOTE!

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.

Читайте также:  DEL

how should we add a button, to trigger this event, so that user will be able to download the CSV file on demand ?

I’ll have «SyntaxError: Unexpected token ILLEGAL» error with the line «fopen(«php://output», «w»);» When I change it to «$fp = fopen(‘stats.csv’, ‘w’);» it doesn’t show error. But then of course it doesn’t work. How should I solve it ?

Add fputcsv($outstream, array_keys($results[0])); just before your foreach to also include column headers.

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.

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 mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Sep 5, 2018 at 13:56
ntzm
4,6632 gold badges30 silver badges35 bronze badges
answered Oct 20, 2008 at 3:16
1
    1
    Using "inline" Content-Disposition means that the browser should attempt to show it without downloading (IE tend to embed an Excel instance for that). "attachment" is what is needed to force a download.
    – Gert van den Berg
    Aug 22, 2017 at 15:51
Add a comment|
9

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:

Get CSV

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 

Источник

How to create a CSV file using PHP?

In this article, we are going to learn about how to create a CSV file using PHP.

Before getting into the topic, first of all, let me explain, what is a CSV file? and how it plays a vital role in data manipulation.

What is a CSV file?

CSV(Comma Separate Values) is a text file that uses comma to separate values. This is used to export data easily and also used to import data from it in an efficient manner.

It stores tabular data where each comma separates the column i.e. shows the end of that particular column. The next line containing another set of values form a new row.

Consider a table that stores the Roll no. , Name and Mark of 3 students:

The above table data may be represented in CSV format as follows:

Roll,Name,Mark 1,John,38 2,Sid,72 3,Jk,20

Using fputcsv() for creating CSV file in PHP

To create CSV file in PHP,following function is used:

fputcsv($file,$fields,$separator,$enclosure);
  • $file : It specifies the file name.
  • $fields : It specifies array of data to be inserted.
  • $separator : It specifies the field separator (By default it is comma i.e “,”).
  • $enclosure : It specifies the field enclosure character.

First two arguments are compulsory whereas last two arguments are optional.

Creating CSV file using static data

The following code illustrates the use of fputcsv():

 // Closing the file fclose($cfile); ?>

Источник

PHP CSV

Summary: in this tutorial, you will learn how to deal with CSV files in PHP, including creating and reading CSV files.

A quick introduction to CSV files

CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in the form of comma-separated values. A CSV file stores each record per line. And it may have a header.

When you open a CSV file using a spreadsheet application, you’ll see that the file is nicely formatted like this:

However, if you view the CSV file in a text editor, it looks like the following:

Symbol,Company,Price GOOG,"Google Inc.",800 AAPL,"Apple Inc.",500 AMZN,"Amazon.com Inc.",250 YHOO,"Yahoo! Inc.",250 FB,"Facebook, Inc.",30Code language: plaintext (plaintext)

Typically, a CSV file uses a comma ( , ) to separate fields in a CSV file. If the field content also contains a comma( , ), the CSV file surrounds that field with double quotes, e.g., “Facebook, Inc..”

Besides using the comma ( , ) character, a CSV file may use other characters to separate fields such as semicolon ( ; ).

Writing to a CSV file

To write a line to a CSV file, you use the fputcsv() function:

fputcsv ( resource $handle , array $fields , string $delimiter = "," , string $enclosure = '"' , string $escape_char = "\\" ) : int|falseCode language: PHP (php)

The following example uses the fputcsv() function to write data to a CSV file:

 $data = [ ['Symbol', 'Company', 'Price'], ['GOOG', 'Google Inc.', '800'], ['AAPL', 'Apple Inc.', '500'], ['AMZN', 'Amazon.com Inc.', '250'], ['YHOO', 'Yahoo! Inc.', '250'], ['FB', 'Facebook, Inc.', '30'], ]; $filename = 'stock.csv'; // open csv file for writing $f = fopen($filename, 'w'); if ($f === false) < die('Error opening the file ' . $filename); > // write each row at a time to a file foreach ($data as $row) < fputcsv($f, $row); >// close the file fclose($f);Code language: HTML, XML (xml)
  • First, define an array that holds the stock data.
  • Second, open the stock.csv file for writing using the fopen() function with the 'w' mode.
  • Third, loop through the $data array and write each each element as a line to the CSV file.
  • Finally, close the file using the fclose() function.

Writing Unicode characters

If you’re dealing with Unicode characters especially creating a CSV file for using Microsoft Excel, you need to change the file header using the fputs() function after opening the file as follows:

 $f = fopen($filename, 'w'); if ($f === false) < die('Error opening the file ' . $filename); > fputs($f, (chr(0xEF) . chr(0xBB) . chr(0xBF))); // support unicode // writing to a CSV file //. Code language: HTML, XML (xml)

Reading from a CSV file

To read a CSV file, you use the fgetcsv() function:

fgetcsv ( resource $stream , int $length = 0 , string $separator = "," , string $enclosure = '"' , string $escape = "\\" ) : arrayCode language: PHP (php)

The fgetcsv() function reads a line of CSV data from the file pointer’s position and places it into an array; each line of the CSV file is an array element.

The function fgetcsv() returns false if there is an error occurred while reading the file or when the file pointer reaches the end-of-file.

The following example shows how to read the stock.csv file created above:

 $filename = './stock.csv'; $data = []; // open the file $f = fopen($filename, 'r'); if ($f === false) < die('Cannot open the file ' . $filename); > // read each line in CSV file at a time while (($row = fgetcsv($f)) !== false) < $data[] = $row; >// close the file fclose($f);Code language: HTML, XML (xml)
  • First, open the stock.csv file for reading using the fopen() function.
  • Second, read each line in the file through the file handle and place it into an array. We use the while loop to read the entire CSV file until the file pointer reached the end-of-file.
  • Third, close the file and display the array.

Summary

  • Use the fputcsv() function to write a row to a CSV file.
  • Use the fgetcsv() function to read a row from a CSV file.

Источник

Оцените статью