tags:

views:

33

answers:

2

I am parsing a CSV data feed sent to me via php. I am turning each line into an array of values.

Here is my code:

$fp = fopen('data.txt','r');

while (!feof($fp))
{
    $line = mysql_real_escape_string(fgets($fp));

    $value_array = explode(',', $line);
}

But if one of the lines looks like this:

"some company, inc.",XC34ET,500

I am getting 4 values:

  1. "some company

  2. inc."

  3. XC34ET

  4. 500

When I really want these 3 values:

  1. some company, inc.

  2. XC34ET

  3. 500

How can I update my script to account for this?

+4  A: 

There is a built-in function for parsing csv files: fgetcsv(). Just replace the fgets() call with it. Using '"' as value for the $enclosure parameter should solve your problem .

greg0ire
+1  A: 

You can use str_getcsv to read in the line and parse it, returning an array

http://uk2.php.net/manual/en/function.str-getcsv.php

adam
Since John is reading the data from a file fgetcsv($fp) seems to be the more "natural" thing to use...
VolkerK
Absolutely. It's late and I misread the question, but left it in for the sake of completeness!
adam
Makes sense ;-) And since there are cases where one wants to parse csv data without a file pointer +1 from me...
VolkerK