如何在 PHP 中解析列中具有多行数据的 csv
考虑像这样的 CSV 文件,
item1,"description 1"
item2,"description 2"
item3,"description 3
description 3 continues on new line"
item4,"description 4"
应该像这样解析 有
item1,"description 1"
item2,"description 2"
item3,"description 3 description 3 continues on new line"
item4,"description 4"
没有办法在 PHP 中解析具有多行值的 CSV?
Consider s CSV file like this
item1,"description 1"
item2,"description 2"
item3,"description 3
description 3 continues on new line"
item4,"description 4"
which should be parsed like this
item1,"description 1"
item2,"description 2"
item3,"description 3 description 3 continues on new line"
item4,"description 4"
Is there a way to parse this CSV in PHP which has multiline values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下是一些如何做到这一点的工作示例。我正在使用 fgetcsv:
CSV in 字符串变量 $CsvString:
CSV in file:
Here are some working examples how to do it. I am using fgetcsv:
CSV in string variable $CsvString:
CSV in file:
fgetcsv
应该能够正确解析它。无论如何,我不建议手动执行此操作,解析 CSV 时有很多这样的问题。
fgetcsv
should be able to properly parse this.I wouldn't recommend doing this by hand anyway, there are many such gotchas in parsing CSV.
基于 StanleyD 答案,但使用临时内存块(而不是写入磁盘)以获得更好的性能:
Based on StanleyD answer, but using a temp memory block (rather than writing to disk) for better performance:
这是使用 PHP 函数
str_getcsv( )
下面是一个示例:
想象一下这样一种情况,您需要一个可以同时处理 URL 和逗号分隔文本的函数。这正是这样工作的函数。只需插入 CSV URL 或逗号分隔的文本即可正常工作。
Here is a quick and easy solution using the PHP function
str_getcsv()
Here is an example:
Imagine a situation where you need a function that works with both URL and comma delimited text. This is exactly the function that works like that. Just simply insert a CSV URL or comma separated text and it work nicely.