Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

csv

explode

"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?

like image 574
ThinkCode Avatar asked Feb 22 '23 11:02

ThinkCode


1 Answers

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.

like image 196
Ben Swinburne Avatar answered Mar 05 '23 16:03

Ben Swinburne