Search code examples
phpcsvfgetcsv

Add a line to top of csv file (first line) with PHP


Need to process large csv files with php. Working with fgetcsv and performance seems pretty good. For even better/ faster processing I would like the csv files to have column names on the first row, which are missing right now.

Now I would like to add a top row with columns names to the csv file with PHP before processing the files with fgetcsv.

Is there a way to add a line top the top of the file with php easily? Or would this mean I have to take a approach like below?

  1. List item
  2. List item
  3. create a temp file
  4. add the column names to this temp file
  5. read original csv file contents
  6. put original csv contents into the temp file
  7. delete original file
  8. rename the temp file

Any feedback on how to do this in the most effective way is highly appreciated. Thanks for your time :)


Solution

    1. Read the CSV file using fgetcsv.
    2. Close the file.
    3. Open the file using "w" (write) mode.
    4. Write the headers.
    5. Close the file.
    6. Open the file using "a" (append) mode.
    7. Write the CSV file using fputcsv. Voila!