1

Here's code full code with removed SQL part. I expect it starts download CSV file with data from database. But when i foreach csv array, it unexpectedly prints all data in almost right format but ignores newlines and puts ' '(space) instead.

$csv = array(
    array('RECID', 'UID', 'Amount', 'Sumbit Date') 
);

while($row = mysql_fetch_row($results)) // SQL query isn't reason 100%
{
    $csv[] = array($row[0], $row[1], $row[2], $row[3]);
}

$fp = fopen('php://output', 'w');

//this part is unexpected
foreach($csv as $line){
    fputcsv($fp, $line);
}

header("Cache-Control:maxage=1");
header("Pragma: public");
header("Content-Type:text\csv; charset=UTF-8" );
header('Content-Disposition: attachment; filename=csv.csv');

fpassthru($fp);

fclose($fp);

If change foreach loop and call fputcsv elements line by line, it does everything correct. Downloading starts and CSV works correct.

fputcsv($fp, $csv[0]);
fputcsv($fp, $csv[1]);
fputcsv($fp, $csv[2]);

however, when you try to go through array with any loop, it ignores newline and outputs data without newline but with ' ' as newline separator. Als it doesn't download it just prints all data in browser.

foreach($csv as $line){
    fputcsv($fp, $line);
}

How to fix this, to make my script works as expected (putting newlines and starting download)?

  • **Warning:** `mysql_*` extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the [mysqli](https://www.php.net/manual/en/book.mysqli.php) or [PDO_MySQL](https://www.php.net/manual/en/book.pdo.php) extension should be used. See also the [MySQL API Overview](https://www.php.net/manual/en/mysqlinfo.api.choosing.php) for further help while choosing a MySQL API. – Dharman Aug 02 '21 at 13:11
  • @Dharman this is really old project. As I said SQL isn't reason of unexpected output. – Nikita Cunskis Aug 03 '21 at 09:14

1 Answers1

0

There was unknown bug, when you put fputcsv line by line it's not important where you write it, however, if you do it in loop, loop must be AFTER all headers!

header("Cache-Control:maxage=1");
header("Pragma: public");
header("Content-Type:text\csv; charset=UTF-8" );
header('Content-Disposition: attachment; filename=csv.csv');

for($i = 0; $i < count($csv); $i++){
    fputcsv($fp, $csv[$i]);
}