How do you EXPLODE CSV line with a comma in value?

谁都会走 提交于 2019-12-07 09:18:16

问题


"AMZN","Amazon.com, Inc.",211.22,"11/9/2011","4:00pm","-6.77 - -3.11%",4673052

Amazon.com, Inc. is being treated as 2 values instead of one.

I tried this $data = explode( ',', $s);

How do I modify this to avoid the comma in the value issue?


回答1:


You should probably look into str_getcsv() (or fgetcsv() if you're loading the CSV from a file)

This will read the CSV contents into an array without the need for exploding etc.

Edit- to expand upon the point made by Pekka, if you're using PHP < 5.3 str_getcsv() won't work but there's an interesting approach here which reproduces the functionality for lesser versions. And another approach here which uses fgetcsv() after creating a temporary file.




回答2:


Use a dedicated CSV library. It's been explained over and over that parsing file formats like CSV manually is asking for trouble, because you don't know all the variations of CSV and all the rules to do it right.



来源:https://stackoverflow.com/questions/8073047/how-do-you-explode-csv-line-with-a-comma-in-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!