Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating csv file with php

Tags:

php

csv

I want to create a csv file, but when I run the code, it returns a blank page and no csv file. I use PHP 5. I use the following code:

<?php     $data = array ('aaa,bbb,ccc,dddd',                    '123,456,789',                    '"aaa","bbb"');      $fp = fopen('data.csv', 'w');     foreach($data as $line){              $val = explode(",",$line);              fputcsv($fp, $val);     }     fclose($fp); ?> 

Thank you!

like image 822
andrei.godea Avatar asked Mar 19 '13 13:03

andrei.godea


People also ask

How do I create a CSV file and download a PHP script?

$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 does PHP Fputcsv work?

fputcsv() function in PHP The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.

How do I pass an array into a CSV file?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.


1 Answers

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="sample.csv"'); $data = array(         'aaa,bbb,ccc,dddd',         '123,456,789',         '"aaa","bbb"' );  $fp = fopen('php://output', 'wb'); foreach ( $data as $line ) {     $val = explode(",", $line);     fputcsv($fp, $val); } fclose($fp); 
like image 138
Baba Avatar answered Oct 09 '22 01:10

Baba