开发者

Trouble parsing CSV data when string contains a comma

开发者 https://www.devze.com 2023-01-11 23:17 出处:网络
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:

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 = e开发者_如何学Cxplode(',', $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?


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 .


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

0

精彩评论

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

关注公众号