7

I need to add columns to an existing csv file ,but i can't find any solution to the problem.I have used "\t" and chr(9) to create columns but no success so please help me by providing me the right solution if any one can

2
  • 1
    can you show your current code? Commented Jul 30, 2010 at 11:29
  • file_put_contents("test.csv","\n".$dob[0].chr(9).$city[0].chr(9).$country[0],FILE_APPEND); my code Commented Jul 30, 2010 at 11:32

2 Answers 2

22

Try this, and have a look at fgetcsv() and fputcsv() in the manual

<?php
$newCsvData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = 'New Column';
        $newCsvData[] = $data;
    }
    fclose($handle);
}

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

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

fclose($handle);

?> 
Sign up to request clarification or add additional context in comments.

1 Comment

This worked well for me for smaller files, however with bigger files, this is at risk of hitting memory limits with the $newCsvData.
-3

Could you try using \r\n instead of \n ?

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.