Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse CSV with values that contain a comma?

Tags:

php

csv

Assuming you have a string as follows:

$str = 'one value, two value, "three, cool value", four value';

How would you make it an array as follows:

$arr = array('one value', 'two value', 'three, cool value', 'four value');

(That's all about CSV and values that contain a comma and thus are double quoted.)

like image 700
Woppie Avatar asked Dec 05 '22 01:12

Woppie


2 Answers

If you are really parsing it from a string, use str_getcsv.

If you are reading data from a file, use fgetcsv.

like image 127
jasonbar Avatar answered Dec 24 '22 15:12

jasonbar


You can use str_getcsv

$str = 'one value, two value, "three, cool value", four value';
var_dump(str_getcsv($str));                                     

Results:

array(4) {
  [0]=>
  string(9) "one value"
  [1]=>
  string(9) "two value"
  [2]=>
  string(17) "three, cool value"
  [3]=>
  string(10) "four value"
}
like image 25
codaddict Avatar answered Dec 24 '22 14:12

codaddict