php csv file download code example

Example 1: php modify csv file

$myfile = 'sample_csv.csv';

$fin = fopen($myfile, 'r');
$data = array();

   /***********
   * header row
   */
$data[] = fgetcsv($fin, 1000);
  /***********
   * data rows
   */
while ($line = fgetcsv($fin, 1000)) {
   echo join(', ', $line).'<br>';
   for($i = 4, $k = count($line); $i < $k; $i++) {
    if ($line[$i] < 1000) {
	    $line[$i] = 10000;
    }
   }
   $data[] = $line;
}

fclose($fin);
   /******************
   * reopen file and
   * write array to file
   */
$fout = fopen($myfile, 'w');
foreach ($data as $line) {
   fputcsv($fout, $line);
}
fclose($fout);

Example 2: php force download csv

header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="ramais.csv"');

  $saida = $stmt->fetchAll(PDO::FETCH_ASSOC);
  echo "id;nome;ramal;email;setor;diretor\r\n";
  foreach ($saida as $s){
  	foreach ($s as $k => $v){
  		echo "{$v};";
	  }
	  echo "\r\n";
  }

Tags:

Php Example