Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and download a csv file from php script?

I am a novice programmer and I searched a lot about my question but couldn't find a helpful solution or tutorial about this.

My goal is I have a PHP array and the array elements are showing in a list on the page.

I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.

I don't know how to do this. I have searched a lot too. But yet to find any helpful resource.

Please provide me some tutorial or solution or advice to implement it by myself. As I'm a novice please provide easy to implement solutions.

My array looks like:

Array (     [0] => Array         (             [fs_id] => 4c524d8abfc6ef3b201f489c             [name] => restaurant             [lat] => 40.702692             [lng] => -74.012869             [address] => new york             [postalCode] =>              [city] => NEW YORK             [state] => ny             [business_type] => BBQ Joint             [url] =>          )  ) 
like image 630
user2302780 Avatar asked Apr 27 '13 11:04

user2302780


People also ask

How do I create a CSV file to download in PHP?

$fh = fopen('somefile. csv', 'w') or die('Cannot open the file'); for( $i=0; $i<count($arr); $i++ ){ $str = implode( ',', $arr[$i] ); fwrite( $fh, $str ); fwrite( $fh, "\n" ); } fclose($fh);

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

export.php csv'); $output = "First Name,Last Name,Email,Phonen"; $sql = 'SELECT * FROM users ORDER BY id desc'; $result = mysqli_query($conn, $sql); while($row = mysqli_fetch_array($result)) { $output . = $row['first_name']. ",". $row['last_name'].

How do I download a CSV file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.

How do I download a CSV file from server?

function writetofile($stringData, $myFile) { $fh = fopen('download/'. $myFile, 'w') or die("can't open file"); fwrite($fh, $stringData); fclose($fh); } $filename = $file. "_". date("d-m-Y_H-i",time()).


2 Answers

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w"); foreach ($array as $line) {     fputcsv($f, $line); } 

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";'); 

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {     // open raw memory as file so no temp files needed, you might run out of memory though     $f = fopen('php://memory', 'w');      // loop over the input array     foreach ($array as $line) {          // generate csv lines from the inner arrays         fputcsv($f, $line, $delimiter);      }     // reset the file pointer to the start of the file     fseek($f, 0);     // tell the browser it's going to be a csv file     header('Content-Type: text/csv');     // tell the browser we want to save it instead of displaying it     header('Content-Disposition: attachment; filename="'.$filename.'";');     // make php send the generated csv lines to the browser     fpassthru($f); } 

And you can use it like this:

array_to_csv_download(array(   array(1,2,3,4), // this array is going to be the first row   array(1,2,3,4)), // this array is going to be the second row   "numbers.csv" ); 

Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {     header('Content-Type: application/csv');     header('Content-Disposition: attachment; filename="'.$filename.'";');      // open the "output" stream     // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq     $f = fopen('php://output', 'w');      foreach ($array as $line) {         fputcsv($f, $line, $delimiter);     } }    
like image 108
complex857 Avatar answered Oct 24 '22 11:10

complex857


I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.

Correct line should look like this:

header('Content-Disposition: attachment;filename="'.$filename.'";'); 

In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:

header('Content-Type: application/csv; charset=UTF-8'); 

Also, I find it more elegant to use rewind() instead of fseek():

rewind($f); 

Thanks for your solution!

like image 40
Luxian Avatar answered Oct 24 '22 09:10

Luxian