5

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

clarkk
  • 27,151
  • 72
  • 200
  • 340
  • Can you replace `\n` with `;` and then use `str_getcsv()` with `;` as your delimiter? – Tim Lewis Dec 29 '15 at 21:57
  • no.. not possible.. the output will be incorrect – clarkk Dec 29 '15 at 21:58
  • the `\n` is a part of the field.. – clarkk Dec 29 '15 at 21:59
  • Did you try explode(';',$str); as a workaround? – bouscher Dec 29 '15 at 22:02
  • can you explain what your expected output will be ? do you want the endlines as part of the field they are near or as actual end lines? say in your example `"1981;2992;19191\n392;488;299\n"some\ntext";199;222"` will translate into `$result=["1981","2992","19191\n392",etc]` or `$result1=["1981","2992","19191"], $result2 = ["392","488","299",etc]` – Cptmaxon Dec 29 '15 at 22:15

2 Answers2

18

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);
lku
  • 1,732
  • 14
  • 20
0

You can try

str_getcsv()

str_getcsv

Since that is not an option here is an answer that might help, or point you in the right direction:

String to filehandle Not sure if that will work for you Good Luck.

Community
  • 1
  • 1
mathius1
  • 1,381
  • 11
  • 17