Jump to content

Export to CSV


onestab

Recommended Posts

I'm trying to export information into a csv file yet each row seems to keep writing over itself until the final product is the last line.  If I use append (a) instead of write (w) for fopen I can get all my rows to export okay except that I don't want to have to use that.  I have tried escapes \r\n, \n etc. and they dont move to the next row but rather work in the individual cell.

 

Thanks for any help,

Alex

 

$list = array("$1,$2,$3,$4,$5");
$fp = fopen('output.csv', 'w');
foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}
fclose($fp);

Link to comment
https://forums.phpfreaks.com/topic/86409-export-to-csv/
Share on other sites

also forgot to put this

 

you dont need fputcsv

 

a normal fwrite will do the same job for ya

 

Below is something i used in a past project. Hope it helps

 

$_file = '../CSV/Admin_List.csv';

$_fp = @fopen( $_file, 'w' );

 

$SQL2 = "SELECT * FROM adminUsers";

$query2 = mysql_query($SQL2);

while ($res2 = mysql_fetch_assoc($query2))

{

$_csv_data= $res2['title'].','.$res2['name'].','.$res2['surname'].','.$res2['email'].','.$res2['postcode'].','.$comments.','.$res2['lastLogin'] .','.$stat. "\n";

@fwrite( $_fp, $_csv_data );

}

@fclose( $_fp );

Link to comment
https://forums.phpfreaks.com/topic/86409-export-to-csv/#findComment-441555
Share on other sites

also forgot to put this

 

you dont need fputcsv

 

a normal fwrite will do the same job for ya

 

The reason for using fputcsv is because it escapes the fields...if, in your example, one of the fields, $res2['title'] perhaps, contained a comma, it would break your csv.  Using fputcsv, it puts quotes around the field so that the comma contained in the field is ignored by most viewers (e.g. Excel)

Link to comment
https://forums.phpfreaks.com/topic/86409-export-to-csv/#findComment-441575
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.