Question

I want to open a csv file named csv.csv with PHP, then add new rows in this file, and finally download the news csv.

The content of csc.csv is:

name, town
name1, town1
name2, town2
name3, town3
name4, town4 

and I want to add these rows:

name5, town5
name6, town6

I made this PHP code but it doesn't work:

<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$file = fopen("csv.csv","r");
$list = array();
while(! feof($file))
  {
  $list[] = array(print_r(fgetcsv($file)));
  }
fclose($file);

$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

outputCSV($list);

function outputCSV($list) {
    $output = fopen("php://output", "w");
    foreach ($list as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
?>
Was it helpful?

Solution

Here is your working code.

<?php

$file = fopen("csv.csv","a+");

$list = array();
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

    foreach ($list as $fields) {
        fputcsv($file, $fields,',');
    }

fclose($file);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv_".time().".csv");
header("Pragma: no-cache");
header("Expires: 0");
?>

UPDATE 1 :

for creating new file without editing existing one.

<?php 
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");


$file = fopen("csv.csv","r");
$list = array();

while(! feof($file))
  {
      $list[] = (fgetcsv($file));
  }
fclose($file);

$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');

$list = array_filter($list);
outputCSV($list);

function outputCSV($list) {
    $output = fopen("php://output", "w");

    foreach ($list as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top