0

Below is my CSV file. As you can see, it's five columns and on the fifth column there are multiple options also comma separated.

column 1,column 2,column 3,column 4,column 5
value,value,value,value,"value, value2, value3"
val,val,val,val,"opt, opt2, opt3"

Here is the code I'm using the parse the above...

$csvData = file_get_contents('test2.csv'); 

$csvNumColumns = 5;
$csvDelim = ',';
$csvEnclosure = '"';

$results = array_chunk(str_getcsv($csvData, $csvDelim, $csvEnclosure), $csvNumColumns); 
print_r($results);

The output of my print_r is as follows...

Array
(
[0] => Array
    (
        [0] => column 1
        [1] => column 2
        [2] => column 3
        [3] => column 4
        [4] => column 5
value
    )

[1] => Array
    (
        [0] => value
        [1] => value
        [2] => value
        [3] => value, value2, value3
val
        [4] => val
    )

[2] => Array
    (
        [0] => val
        [1] => val
        [2] => opt, opt2, opt3
    )
)

As you can see, for some reason this isn't being parsed correctly. I suppose I could explode it by new lines and then again by comma...however, I would like to understand why this isn't working.

1 Answer 1

0

str_getcsv() is meant to return one row only, but you want all rows. Instead, use fgetcsv in a loop. Since fgetcsv uses a file pointer, it can keep track of the position where it stopped parsing the previous row, so the next time you call it, parsing continues at the correct position(which is the next csv row).

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you can explode("\n") the string then loop through each line and feed to str_getcsv
@ina that would fail if any fields contain new line characters.

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.