PHP use the fputcsv CSV to write same data in column for each row

3.9k views Asked by At

I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow There is not separator only a delimiter which is the semi colon.

I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.

So far it adds the new column with but I can't understand how to put the same value in each line for that column ?

<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?

if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
        $data[] = 'ExempleRow';
        $newCsvData[] = $data;
    }
    fclose($handle);
}

$handle = fopen('exemple.csv', 'w');

foreach ($newCsvData as $line) {
   fputcsv($handle, $line,';',' ');
}

fclose($handle);

?> 
1

There are 1 answers

2
David Jones On BEST ANSWER

If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.

$handle = fopen('exemple.csv', 'w');
$keys = false;

foreach ($newCsvData as $line) {
   if ($keys === false) {
       //$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
       fputcsv($handle, array_keys($line), ';', '');
       $keys = true;
   }
   fputcsv($handle, $line,';',' ');
}

fclose($handle);