문제

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

도움이 되었습니까?

해결책

  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!

다른 팁

Please try this .. much simpler and straight to the point.

  $file = 'addline.csv';
  $header = "Name, IP,  Host, RAM, Task, NS \r\n";
  $data = file_get_contents($file);
  file_put_contents($file, $header.$data);

You are done. Hope this helps...

Just do it the way you provided. there is no easy way to extend a file on the beginning instead of the end. it's like writing on paper. it's easy to add new lines below your text but you can't write above you text.

Don't use fopen($file, "r+") or fopen($file, "c") as this will remove existing lines at the beginning or even all lines of your file.

Why not to define header in your code manually, especially if every file has the same header? If you really need to insert header into CSV files before you process them maybe you should consider using sed like this: sed -i 1i'"header 1","header 2"' file.csv

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top