Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use fgetcsv with strings [duplicate]

Tags:

php

csv

How to use fgetcsv where the input is a string and not a resource?

How to convert the string into a resource?

fgetcsv expects a file handle resource

$str = "1981;2992;19191\n392;488;299\n"some\ntext";199;222";
$array = fgetcsv($str);

Can not use str_getcsv because then I have to split the string by \n before str_getcsv.. If some of the fields contains \n then the output will be incorrect

like image 764
clarkk Avatar asked Dec 06 '22 19:12

clarkk


1 Answers

There is str_getcsv function, it can parse CSV string into an array.

Update: if you cannot use str_getcsv function, try to convert string to stream and use it in fgetcsv:

$stream = fopen('php://memory', 'r+');
fwrite($stream, '1981;2992;19191\n392;488;299');
rewind($stream);
$array = fgetcsv($stream);
like image 176
lku Avatar answered Dec 09 '22 14:12

lku