0

I thought it will be easy task, but simple I'm not able to output data from an array to CSV file (saved on a server).

Code for that part looks like:

$fp = fopen('missing-skus.csv', 'w');

foreach ($missing_array as $lines) {
    fputcsv($fp, $lines);
}

fclose($fp);

$missing_array looks like:

Array
(
    [0] => 5804
    [1] => 5803
    [2] => 5802
    [3] => 5801
    [4] => 5800
    [5] => 5799
    [6] => 5798
    [7] => 5797
    [8] => 5796
    [9] => 5795
    [10] => 5794
    [11] => 5793
    [12] => 5792
    [13] => 5791
    [14] => 5790
    [15] => 5789
    [16] => 5788
    [17] => 5787
    [18] => 5786
    [19] => 5785
    [20] => 5784
    [21] => 5783
    [22] => 5782
    [23] => 5781
    [24] => 5780
    [25] => 5779
)

No matter what, file is always blank. Any clue what I have missed?

4
  • Does the server have write access to that file? You can also use 'php://output' as the filename to output to the browser as a test. Commented Aug 6, 2014 at 20:23
  • Yes, it does - an example from php.net/manual/en/function.fputcsv.php works fine. Commented Aug 6, 2014 at 20:25
  • The second arg to fputscsv is an array of fileds. You are passing a string or int. Commented Aug 6, 2014 at 20:28
  • 1
    Have you tried: fputcsv($fp, array($lines));. The second param should be an array, even if you only have 1 column. Commented Aug 6, 2014 at 20:28

1 Answer 1

1

The second argument to fputcsv is an array of fields. You are passing a string or integer.

If you want one line with the array values as fields, in CSV fashion, then just:

$fp = fopen('missing-skus.csv', 'w');
fputcsv($fp, $missing_array);

If you just want each array value on one line then no need for fputcsv:

file_put_contents('missing-skus.csv', implode("\n", $missing_array));
Sign up to request clarification or add additional context in comments.

2 Comments

That works as well jerremyharris solution to use fputcsv($fp, array($lines));
Yes, but why open a file loop through an array and use fputcsv to write one item to each line and then close the file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.