How to create a CSV file in PHP code?

25 pts.
Tags:
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?

Answer Wiki

Thanks. We'll let you know when a new response is added.

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>

Discuss This Question: 2  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • Texmansru47
    [...] How to create a CSV file in php code? New Question Created. by Texmansru47. IT answers - http://itknowledgeexchange.techtarget.com/itanswers [...]
    0 pointsBadges:
    report
  • Sourour
    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 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following