2

I need to save data array to CSV file. The problem is the following: When I open CSV file, I see that 0 row of an array is saved at the same row as a header. Also the last column of a header contains 0, i.e. 'www0'. How to avoid this?

        header("Content-type: text/csv");
        header("Pragma: no-cache");
        saveCSV($solutionCSV);

function saveCSV($data) {
    $outstream = fopen("schedule.csv", "a");

    $headers = 'xxx, yyy, zzz, www';
    fwrite($outstream,$headers);

    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals);
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
}
1
  • This is somewhere where a simple foreach would be better than array_walk(), especially if you're not using an anonymous function, since a second call to saveCSV() will cause a fatal error along the lines of Cannot redeclare function __outputCSV(), already declared in.... A foreach will be shorter, easier to understand when you come back to the code a year from now and more efficient. Commented May 28, 2012 at 21:23

1 Answer 1

1

You need a newline after the headers. Note the change from single- to double-quotes to enable escaping.

$headers = "xxx, yyy, zzz, www\n";

If this trips up Windows, use \r\n:

$headers = "xxx, yyy, zzz, www\r\n";

Alternatively, you can rely on fputcsv to write the headers, too. This is probably the safest method as it will result in a consistent format.

$headers = array('xxx', 'yyy', 'zzz', 'www');
fputcsv($outstream, $headers);
Sign up to request clarification or add additional context in comments.

2 Comments

Your second solution works fine for me. The last one does not work, I don't know why - It writes Array0 in the first row.
@KlausosKlausos - Did you change fwrite to fputcsv when trying that last version?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.