2

I create a CSV file with one column using PHP. I do that iteratively in a loop. What I want now is to add a second column inside this CSV. I want to that after the end of the loop. Is it possible doing this with php?

for ($number = 1; $number <= 26; $number++) {
  #create CSV With one column
}

#append one more column to existing CSV
5
  • Do it within the loop Commented Jul 6, 2015 at 14:23
  • 3
    You will need to open the file, read in each line, append to the end of each line, and write to a new file. It is simply too difficult to append to the end of each line inside the same file. But... you could just keep it all in memory and write the file once you are done - a much better design. Commented Jul 6, 2015 at 14:23
  • Or create a temporary file, then read that and add a new column, write to final file, delete temp file. So many possibilities. :) Commented Jul 6, 2015 at 14:27
  • why not build both columns at the same point? Once you've written out as csv, it's just a huge blob of text as far as PHP is concerned. you'd have to RE-read the entire file, line-by-line... Commented Jul 6, 2015 at 14:27
  • Thanks for the answers. I will try what you recommended. Commented Jul 6, 2015 at 14:31

1 Answer 1

5

You can do it this way:

$a = file('csv.csv');// get array of lines
$new = '';
foreach($a as $line){
    $line = trim($line);// remove end of line
    $line .=";new column";// append new column
    $new .= $line.PHP_EOL;//append end of line
}
file_put_contents('csv.csv', $new);// overwrite the same file with new data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.