Carol.Kar
Carol.Kar

Reputation: 5355

Add array line by line to csv file

I am using PHP 7.1.33 and I want to add an array line by line to a file.

I tried the following:

<?php

$posts = ["a", "b", "c", "d"];

function array2csv($data, $delimiter = ';', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('data/array2file.csv', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

array2csv($posts);


However, I get the following error:

fputcsv() expects parameter 1 to be resource, boolean given

I just want to have a csv file that looks like the following:

| a |
| b |
| c |
| d |

So for each line the output of the array.

Any suggestions what I am doing wrong?

I appreciate your replies!

Upvotes: 0

Views: 80

Answers (1)

realization
realization

Reputation: 597

<?php
$posts = ["a", "b", "c", "d"];

function array2csv($data, $delimiter = ';', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('data/array2file.csv', 'w');
    foreach ($data as $item) {
        fputcsv($f, [$item], $delimiter, $enclosure, $escape_char);
    }
    fclose($f);
}

array2csv($posts);

Upvotes: 1

Related Questions