It sounds like you have the actual comma separated content in a variable which you are able to print to the screen. If all you are looking for is to write that content to a file you can check this tutorial:
The useful code snippet is:
If you live outside the United States, by submitting your email address you consent to having your personal data transferred to and processed in the United States.
Maybe you will need to create a array of values and insert into the file instead of sending one by one.
Try the following
class Format { static public function arr_to_csv_line($arr) { $line = array(); foreach ($arr as $v) { $line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"'; } return implode(",", $line); } static public function arr_to_csv($arr) { $lines = array(); foreach ($arr as $v) { $lines[] = self::arr_to_csv_line($v); } return implode("n", $lines); } }