开发者

Dealing with commas in CSV

I get a CSV data from a SOAP call in php. Unfortunately, the data may have co开发者_运维问答mmas in it. It is formatted correctly as in

1,name,2,lariat,3,"first, last",5,NMEA,...

I need to parse it to individual values in either php or javascript. I have browsed through threads on stack overflow and elsewhere but have not found a specific solution in php / javascript.

The approach I am currently using is

$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$pattern = '/,|,"/';
$t2=preg_replace ('/,|(".*")/','$0*',$subject);
$t2=str_replace(',','*',$t2);
$t2=str_replace('*',',',$t2);

Where * is the deliminator, but the preg_replace generates an extra *. I have tried a couple of other approaches involving preg_match and other preg_ functions but did not succeed in having any kind of a clean split.

Any suggestion on how to split up CSV data that contains commas in it?


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.

$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$array = str_getcsv($subject, ",", '"');

print_r($array);
// Prints:
Array
(
    [0] => 123
    [1] => name
    [2] => 456
    [3] => lryyrt
    [4] => 123213
    [5] => first,last
    [6] => 8585
    [7] => namea3
)


Just another way to convert a csv file to an associative array.

<?php
//
// Convert csv file to associative array:
//

function csv_to_array($input, $delimiter=',')
{
    $header = null;
    $data = array();
    $csvData = str_getcsv($input, "\n");

    foreach($csvData as $csvLine){
        if(is_null($header)) $header = explode($delimiter, $csvLine);
        else{

            $items = explode($delimiter, $csvLine);

            for($n = 0, $m = count($header); $n < $m; $n++){
                $prepareData[$header[$n]] = $items[$n];
            }

            $data[] = $prepareData;
        }
    }

    return $data;
}

//-----------------------------------
//
//Usage:

$csvArr = csv_to_array(file_get_contents('test.csv'));

?>


For JavaScript use jQuery-CSV

If you're already using jQuery, just add the jquery-csv.js module to expose the extension methods. Then just convert the CSV directly to a JavaScript array.

If you're only parsing the following will convert it to a one-dimensional array:

$.csv.toArray(csv);

If you have a multi-line CSV string the following will convert it to a two-dimensional array:

$.csv.toArrays(csv);

Note: all the different line endings are detected and split correctly using a smart regex.

The default delimiter is a double-quote (") and the default separator is a comma (,) but you can change use custom settings by specifying them in the method call.

Ex:

$.csv.toArray(csv, { separator:';', delimiter:"'" });

I created the project to provide an end-to-end CSV parser written in JavaScript that takes the guesswork out of importing-exporting CSV.

Doing the heavy lifting on the client removes unnecessary load on the server and removes any unnecessary AJAX round-trips to the server.

Update:

If you're looking for a server-side solution, the library also works on Node.js.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜