tags:

views:

204

answers:

3

I have a csv file which looks like this

$lines[0] = "text, with commas", "another text", 123, "text",5;
$lines[1] = "some without commas", "another text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";

And I would like to have a table:

$t[0] = array("text, with commas", "another text", "123", "text","5");
$t[1] = array("some without commas", "another text", "123", "text");
$t[2] = array("some text, with comma,s or no", NULL , "123", "text");

If I use split($lines[0],",") I'll get "text" ,"with commas" ... Is there any elegant way to do it?

+4  A: 

You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.

Matt
Is there similar function for a line?
liysd
Yes, `fgets` will get an entire line.
webdestroya
@liysd - Yes, you can pass a string to [str_getcsv](http://php.net/str_getcsv), however this is only available in PHP 5.3+. The comments section has a replacement, though.
Matt
I mean a line is input not a file handle
liysd
If the line is input, not from a file, please clarify that in the question.
salathe
+2  A: 

In addition to Matt's suggestion, you can also use SplFileObject to read in the file:

$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(',', '"', '\\'); // this is the default anyway though
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}

source: http://de.php.net/manual/en/splfileobject.setcsvcontrol.php

Gordon
A: 

Hi,

here is also a simple method to get read csv file.

$sfp = fopen('/path/to/source.csv','r'); 
$dfp = fopen('/path/to/destination.csv','w'); 
while ($row = fgetcsv($sfp,10000,",","")) { 
 $goodstuff = ""; 
 $goodstuff = str_replace("¦",",",$row[2]); 
 $goodstuff .= "\n"; 
 fwrite($dfp,$goodstuff); 
} 
fclose($sfp); 
fclose($dfp);
VAC-Prabhu