Jump to content

unexpected output when downloading .csv using header function


arturo322

Recommended Posts

Hi i turned my output_buffering to true on my php.ini because i need some of its features for trailing the system my problem now is when im getting .csv file using header function, it seems that it gives me the source code of the interpreted code instead of the expected .csv contents.

 

Here is the source code

 

 

 

echo $who;

echo $ecrn;

$myFile = "($who)$info_value[RecordName]-$ecrn";

header('Content-Type: text/csv; charset=utf-8');

$content = "Content-Disposition: attachment; filename=".$myFile.".csv";

header($content);

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

$sql = "SELECT * FROM classrecordvalue";

$query = mysql_query($sql);

// loop over the rows, outputting them

while ($row = mysql_fetch_array($rows)) fputcsv($output, $row);

 

 

im just wondering does output_buffering true  in php.ini affect the output here? if so

any other suggestions there of how i can download .csv files using php? thank you much for the people who will help

Change your code to:

<?php
      echo $who;
      echo $ecrn;
      $myFile = "($who){$info_value['RecordName']}-$ecrn";
      header('Content-Type: text/csv; charset=utf-8');
      $content = "Content-Disposition: attachment; filename=".$myFile.".csv";
      header($content);
      $sql = "SELECT * FROM classrecordvalue";
      $query = mysql_query($sql);
      // loop over the rows, outputting them
      while ($row = mysql_fetch_array($rows, MYSQL_NUM)){
      	 echo '"' . implode('","',$row) . '"' . "\n";
      }
?>

or you can write a temp file and then use readfile().

<?php
      echo $who;
      echo $ecrn;
      $myFile = "($who){$info_value['RecordName']}-$ecrn";
      header('Content-Type: text/csv; charset=utf-8');
      $content = "Content-Disposition: attachment; filename=".$myFile.".csv";
      header($content);
      $sql = "SELECT * FROM classrecordvalue";
      $query = mysql_query($sql);
      // loop over the rows, outputting them
      $fn = tempnam('/tmp','csv');
      $tmp = array()
      while ($row = mysql_fetch_array($rows, MYSQL_NUM)){
      	 tmp[] = '"' . implode('","',$row) . '"';
      }
      file_put_contents($fn,implode("\n",$tmp));
      $fs = filesize($fn);
      header("Content-Length: $fs");
      readfile($fn);
      unlink($fn); //delete the temporary file
?>

 

Ken

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.