Rich
Rich

Reputation: 512

my csv file only gets one row

I'm outputting a temporary table to a csv file, but it only gets one row ?

here is the code

$fileName = fopen('cmv_sailings.csv', 'w');

while ($i = mysql_fetch_assoc($export)) {
    $ship = $i['code'];
    $title = $i['title'];
    $sailDate = $i['sailDate'];
    $fromPort = $i['fromport'];
    $nights = $i['nights'];
    $grade = $i['type'];
    $fare = $i['fare'];
    $offer = $i['offerFare'];
    $deposit = $i['deposit'];

    $content = $ship.','.$title.','.$sailDate.','.$fromPort.','.$nights.','.$grade.','.$fare.','.$offer.','.$deposit.'\n';

    fwrite($fileName, $content);
}

fclose($filename);

I haven't got a clue now. I was trying to use fputcsv but I can't get that working either

Upvotes: 1

Views: 751

Answers (4)

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

use like this, The main problem I can seen in your code is using single quote for \n that's why new line character is not getting added in your csv file and you are getting your result in one single line

$content = $ship.','.$title.','.$sailDate.','.$fromPort.','.$nights.','.$grade.','.$fare.','.$offer.','.$deposit."\n";
fwrite($fileName, $content);

Upvotes: 0

Nikola
Nikola

Reputation: 554

  1. Using mysql_ not a good idea, for now ok, but in future, migrate to PDO or mysqli
  2. Preparing the CSV manually, not a good idea, special characters must be escaped, use fputcsv description here
  3. Why you have only one row in your CSV, i think is because of some formatting problems (or missing formatting), coming from your way of formatting.

Upvotes: 0

John Dvorak
John Dvorak

Reputation: 27287

$content = $ship. ... .'\n';

You are appending a backslash and n to the file, not the newline character. Try this:

$content = $ship. ... ."\n";

Upvotes: 0

Asaph
Asaph

Reputation: 162801

In your code, at the end of your $content variable assignment, change '\n' to "\n". In php, escape sequences are not interpolated when using single quotes. They are interpolated when using double quotes. You're getting a literal backslash, followed by a literal n instead of the line break you're looking for.

As for using fputcsv(), that may not have worked for you due to using the incorrect line breaks for your platform. This happens on the Mac. If this was your issue, try turning on auto_detect_line_endings before your file parsing code. You can do it at runtime using ini_set() like this:

ini_set('auto_detect_line_endings', '1');

Upvotes: 3

Related Questions