PHP dealing with commas in CSV data

Dealing with commas in CSV

Look carefully the data, there are multiple commas ‘,’ inside the address field. When transform the data to array, the output will be each commas separated in one array value.
Example: (wrong way)

$data = 'Hyatt Regency Marina,"1441 Quivira Road, San Diego, California, USA, 92109",+1 619 224 1234';
$linearray = explode(',',$data );
print_r($linearray);
//Output:
Array
(
    [0] => Hyatt Regency Marina
    [1] => "1441 Quivira Road
    [2] =>  San Diego
    [3] =>  California
    [4] =>  USA
    [5] =>  92109"
    [6] => +1 619 224 1234
)

Don’t attempt to do this with a regular expression. Just use str_getcsv()! The third parameter informs str_getcsv() to look for quote-enclosed fields.
Example: (correct way

$data = 'Hyatt Regency Marina,"1441 Quivira Road, San Diego, California, USA, 92109",+1 619 224 1234';
$linearray = str_getcsv($data, ",", '"');
print_r($linearray);
//Output:
Array
(
    [0] => Hyatt Regency Marina
    [1] => 1441 Quivira Road, San Diego, California, USA, 92109
    [2] => +1 619 224 1234
)

By Keenlio, November 12, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


4 × = twenty eight

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>