How to parse CSV with comma-containing values?

Assuming you have a line like this:

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

How would you make an array like this:

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

(All about CSV and values ​​containing a comma and thus double quotes).

+4
source share
6 answers

If you really parse it from a string, use str_getcsv .

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

+8
source

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"
}
+5
source

, 5.3.0 , str_getcsv. PHP, fgetcsv 'var' . .

+2

You can watch fgetcsv .

+1
source

str_getcsv () uses this function with an attachment like '\"'.

It looks like this: $csv = str_getcsv($csvstring,',','\"');

0
source

There are two ways.

  • If you are going to specify records, indicate each record. Then explode the string with "," (with quotes).

  • Replace commas with something unusual before parsing. Like {|}

-1
source

Source: https://habr.com/ru/post/1762594/


All Articles