如何在字符串中使用fgetcsv [英] how to use fgetcsv with strings

查看:95
本文介绍了如何在字符串中使用fgetcsv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 fgetcsv ,其中输入是字符串而不是资源?

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

如何转换

fgetcsv 需要文件句柄资源

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

不能使用 str_getcsv 因为我有在 str_getcsv 之前用 \n 分隔字符串。如果某些字段包含 \n ,则输出将不正确

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

推荐答案

str_getcsv 函数,它可以将CSV字符串解析为数组。

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

更新:如果无法使用 str_getcsv 函数,请尝试将字符串转换为流,并在 fgetcsv :

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);

这篇关于如何在字符串中使用fgetcsv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆