25 pts.
 How to create a CSV file in PHP code?
CSV, PHP
I need to create a physical CSV file from PHP code. I have many solutions to get the results to print to a screen, but I need a file... any ideas?

Software/Hardware used:
ASKED: October 15, 2008  6:03 PM
UPDATED: April 19, 2013  3:27 PM

Answer Wiki:
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:
<pre>
$myFile = "testFile.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "one, two, three, four";
fwrite($fh, $stringData);
fclose($fh);
</pre>
Last Wiki Answer Submitted:  April 19, 2013  3:28 pm  by  Michael Tidmarsh   11,410 pts.
All Answer Wiki Contributors:  Michael Tidmarsh   11,410 pts. , Tombrady   250 pts. , Texmansru47   25 pts. , Vernond   15 pts.
To see all answers submitted to the Answer Wiki: View Answer History.


Discuss This Question:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _


 

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);
      }
      }
 435 pts.