Answers for "php writing to a csv file"

PHP
1

php write csv

// open the file "demosaved.csv" for writing
$file = fopen('demosaved.csv', 'w');
 
// save the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
 
// Sample data. This can be fetched from mysql too
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
);
 
// save each row of the data
foreach ($data as $row)
{
fputcsv($file, $row);
}
 
// Close the file
fclose($file);
Posted by: Guest on November-18-2020
2

php open csv

$csvFile = file('../somefile.csv');
    $data = [];
    foreach ($csvFile as $line) {
        $data[] = str_getcsv($line);
    }
Posted by: Guest on September-02-2020
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);
Posted by: Guest on May-04-2020

Browse Popular Code Answers by Language