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!
$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);
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With