0

Here's my code:

<?php
error_reporting(E_ALL ^ E_NOTICE);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('field1', 'field2'),';','"');
mysql_connect('localhost', 'usr', 'psswd');
mysql_select_db('db');
$rows = mysql_query('
SELECT
field1,
field2
FROM table
');
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
mysqli_close($con);
?>

The result is that ";" delimiter is only used in the header of the csv file, not in every row. Tanks.

jm_
  • 631
  • 2
  • 12
  • 20
  • Why didn’t you use the same parameters when printing the rows? – Gumbo Oct 24 '14 at 19:02
  • Why would you exepect fputcsv to 'remember' how you used it last time? You're not specifying any delimiter options for the fputcsv call inside your `while()` loop, so fputcsv is going to use its defaults. – Marc B Oct 24 '14 at 19:07
  • Ow! forgive me. Didn't realize my silly mistake. – jm_ Oct 24 '14 at 19:22

1 Answers1

4

You're not setting "dialect" (delimiter and enclosure) when you iterate trough rows. That is: ';','"' part. Just use:

while ($row = mysql_fetch_assoc($rows)){
    fputcsv($output, $row,';','"');
}

Also for this particular use case mysql_fetch_row() may be more appropriate (you avoid having string based indexes and just use numeric ones).

Side note: mysql_ functions family is obsolete, if it's possible try to replace it with mysqli_ or PDO.

Community
  • 1
  • 1
Vyktor
  • 20,559
  • 6
  • 64
  • 96