0

Is it possible to convert a coma separated string to a csv file in php?

str = "apple, orange, banana, lychee, grapes, pineapple, strawberry, mango";
Becky
  • 5,467
  • 9
  • 40
  • 73

1 Answers1

2

Have you tried this?

$str = "apple, orange, banana, lychee, grapes, pineapple, strawberry, mango";
$data = str_getcsv($str);
print_r($data);

To save $data to a file you can use fputcsv

//Open file
$fp = fopen('file.csv', 'w');

//Add $data to file
fputcsv($fp, $data);

//Close file.
fclose($fp);
Daniel Dudas
  • 2,972
  • 3
  • 27
  • 39
  • Thanks +10. What about giving it a file name? Basically I will be saving this on the server. – Becky Apr 05 '16 at 11:49
  • 1
    I updated my answer with how to save a single line to file. If you want to save more just add more `fputcsv()` or include in a `for-loop` between `fopen` and `fclose`. – Daniel Dudas Apr 05 '16 at 11:52
  • Thanks. What exactly happens is I create this coma separated string on the fly. Then I'm looking for a way to save this coma separated string as a CSV file named `converted.csv` on the same location where the php is. – Becky Apr 05 '16 at 11:57