0

I am reading a comma deliminated CSV file line by line and then separate each column value using PHP explode function. The problem is that there are some columns which itself have comma (,) values in it so they are also exploded.

A row of data:

03,1392,06,1000,1,"1000,36,21,68",4,AF,TJ,AF,44071000

Here "1000,36,21,68" must be considered as a single value but PHP explode also breaks it. I know this is how explode works but is there any alternate function which can be used in this case. Also i would need to remove the double quotes (") from both sides from this value.

3
  • 1
    Or php.net/fgetcsv if you are reading from file. Commented Dec 29, 2013 at 11:30
  • or preg_split() Commented Dec 29, 2013 at 11:31
  • @hal9000 preg_split appears to be good idea, what should be the regex in this case? Commented Dec 29, 2013 at 11:32

1 Answer 1

2

Don't try using explode and parsing it yourself:

use PHP's built-in str_getcsv() function

or use fgetcsv() to read and parse each line directly from file

EDIT

If you're feeling really adventurous, you can use SPL to read and parse the file

$file = new SplFileObject("data.csv");
while (!$file->eof()) {
    var_dump($file->fgetcsv());
}

or

$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
    var_dump($fields);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great It works! I am using fopen and fgets to read each line. Is fopen better or SplFileObject?
I tend to use SplFileObject because it gives a degree cleaner coding when setting flags to manipulate the way the file is parsed, but fopen() and fgetcsv() is really just as easy to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.