开发者

parsing CSV files with escaped characters in PHP

开发者 https://www.devze.com 2023-02-16 14:45 出处:网络
I\'m trying to use a Google Docs spreadsheet as a datab开发者_StackOverflowase for a very simple project, and I feel I have a working version now, based on yc\'s answer for this question:

I'm trying to use a Google Docs spreadsheet as a datab开发者_StackOverflowase for a very simple project, and I feel I have a working version now, based on yc's answer for this question: using Google Docs as a database?

My problem is that now I arrived where I might need to do something with the escaped characters. I don't know if there is a standard implementation for CSV or it's different from program to program, but here is what Google Docs is doing:

If I have the following source data (a,b,c,d,e meaning 5 separate columns)

a     b     c     d1, d2, d3, d4     e1, e2, "e3, e4", e5, "e6"

Then it produces the following line:

a,b,c,"d1, d2, d3, d4","e1, e2, ""e3, e4"", e5, ""e6"""

As far as I understand, it wraps the whole field in "field" if it finds something and escapes the " as "". Maybe we just need to unescape "" into " and unwrap the field from "field" into field.

Is there any way to parse this version of CSV in PHP? If it's really hard, I still have an idea how to replace the characters inside Google Docs, and publish them on a different sheet, but I hope it is possible to solve it in a simple PHP function.

Alternative solution: maybe it's much easier to just fetch the XML in RSS or ATOM format, but I don't know how to parse those formats.


Use str_getcsv, using the quote itself as an escape character, something like:

$array = str_getcsv($str, ',', '"', '"');

If you are parsing from a file or a network stream, also consider using fgetcsv.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号