Question

I am trying to export database data into .csv via php. After a certain length of data it doesn't save the query into a .csv file but displays it on the screen. It looks like it's independent on which records are queried, and it also seems to be independent of any special characters.

$handle = fopen("php://output", "w");
fputcsv($handle, array('Name','Text','Link','Category','Price','Package', 'Date of upload','Date of verification','Date of expiry','Status','Clk'));
for ($c=0; $c<$num_rows; $c++)
{
    $row2[$c][0] = iconv("UTF-8","WINDOWS-1257",html_entity_decode( $row2[$c][0] ,ENT_COMPAT,'utf-8'));
    $row2[$c][1] = iconv("UTF-8","WINDOWS-1257",html_entity_decode( $row2[$c][1] ,ENT_COMPAT,'utf-8'));
    fputcsv($handle, array($row2[$c][0], $row2[$c][1], $row2[$c][2], $row2[$c][3], $row2[$c][4], $row2[$c][5], $row2[$c][6], $row2[$c][7], $row2[$c][8], $row2[$c][9], $row2[$c][10]));
}
fclose($handle);

header('Content-Type: text/csv; utf-8');
header("Content-Disposition: attachment; filename=".$filename);
header("Pragma: no-cache");
header("Expires: 0");

11 columns, 18 records. With 19 records it's not working.

Am I missing some setting?

Was it helpful?

Solution

Place the headers before the output!


If you convert to utf use:

iconv("WINDOWS-1257", "UTF-8", ...

The order of arguments was wrong

OTHER TIPS

Alternatively to the great answer by @hex2mgl 'set headers before fopen()', you could use output buffering to prevent fputcsv from printing directly to the screen instead of into the handle:

ob_start();
$out = fopen('php://output', 'w');
$csv = ob_get_clean();
fclose($out);

Update:

Just found that the new PHP i/o php://temp does a much better job and doesn't require output buffering. Uses memory first (upto 5mb or whatever you specify), then will switch to disk if needed:

$fiveMBs = 5 * 1024 * 1024;
$stream = fopen("php://temp/maxmemory:$fiveMBs", 'r+');

Here:

$handle = fopen("php://output", "w");

You are getting the handle for the standard output (witch is kind of a file).

Guess you meant:

$handle = fopen($filename, "w");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top