0

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);

?> 
Mickael B
  • 13
  • 1
  • 3
  • Why would the number of lines changing for each CSV be an issue? You are appending one line at a time. Or do you mean each ROW has a different number of COLUMNS? – David Jones Nov 21 '14 at 09:39
  • no sorry my question is misleading. Basically I need to add a column with a title for the header, and fill the rest of the column with the same value for each line. Right now the entire column (including header title) is filled with the value. I need the header to have a title like: "Header Title" and the rest of the column with "My value for each line". – Mickael B Nov 21 '14 at 09:45

1 Answers1

0

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);
David Jones
  • 4,275
  • 6
  • 27
  • 51