user1453786
user1453786

Reputation: 225

Export an array to CSV failure: string given

I can't solve a problem occurring when I try to export an array to a CSV file. I have used this function several times without problem but here I do not see where my mistake is.

I set an array:

$mytags= array();

I populate it by a loop. When I print the content through print_r($mytags); it seems to be OK, here some examples of my output:

Array ( [0] => [1] => air-travel [2] => airports [3] => security-airport [4] => city-airport  ... )

After that I try to export the result to CSV by fputcsv:

$fp = fopen('file.csv', 'w');
foreach ($mytags as $fields) {
    fputcsv($fp, $fields);
}

But I get this error:

Warning: fputcsv() expects parameter 2 to be array, string given in C:\wamp\www\tests\capturetags.php on line 55

Could the problem be that there is only one field? Alternatively, I tried to replace $fields by $mytags to write the CSV, and in this case I get a 4GB files, so it's not the Does someone see how to record thhis unique field in a CSV file?

Upvotes: 1

Views: 8889

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174957

The error is very clear, $fields is not an array, it is a string. You need an array.

fputcsv($fp, $mytags);

Without a foreach loop will do the job.

Upvotes: 6

Related Questions