views:

43

answers:

2

Let's suppose I have the following line in a CSV file (I removed the header row in this example):

"500,000",2,50,2,90000

I have a PHP script read the CSV file, break the file into individual lines, and store each line in an array called $linearray. Then, I use a foreach loop to look at each line individually.

Within the foreach loop, I break the line into separate variables using the following function:

$line = str_replace("'","\'",$line);

From here, I insert the values into separate columns within a MySQL database. The script works. The values are inserted into a database, but I run into a problem. I want:

"500,000"  |  2  |  50  |  2  |  90000

But I get this:

"500  |  000"  |  2  |  50  |  2  |  90000

The script isn't smart enough to understand it should skip commas within quotation marks. Do you know how I can alter my script to make sure I get the output I'm looking for?

Thanks.

A: 

Try fgetcsv.

Emil Vikström
+1  A: 

You can use the str_getcsv function

print_r(str_getcsv($line));

Outputs:

Array
(
    [0] => 500,000
    [1] => 2
    [2] => 50
    [3] => 2
    [4] => 90000
)

Similar to fgetcsv() this functions parses a string as its input unlike fgetcsv() which takes a file as its input.

Russell Dias
Note that str_getcsv only works in PHP 5.3 and above. For earlier versions, "save" the string to the php://memory special file and use fgetcsv to parse it. Not that str_getcsv is really relevant to this question since the OP specifically have a file, so reading it one line at a time probably makes sense.
Emil Vikström
@Emil Yeah, I was just showing him an example using the `$line` variable he already had. At the bottom I stated what he should do for a csv file.
Russell Dias