12

I've a csv file with the following structure:

a; b; c,c c; d

When I try to process it, it says offset 2 and 3 are undefined. Took me a while to realize it is caused by the , and have no idea how to solve this. If I remove the , everything runs fine.

Here's my processing function:

function process_csv($file) {

    $file = fopen($file, "r");
    $data = array();

    while (!feof($file)) {
        $csvdata = fgetcsv($file);

        $data[] = explode(';', $csvdata[0]);
    }

    fclose($file);
    return $data;
}

Tried fgetcsv($file); as fgetcsv($file, '"'); but didn't help.

1
  • 5
    The separator is the third argument to fgetcsv. Commented Apr 7, 2015 at 8:43

1 Answer 1

20

Your problem is, that fgetcsv uses , as delimiter by default. If you change it to ; you don't need to explode.

function process_csv($file) {

    $file = fopen($file, "r");
    $data = array();

    while (!feof($file)) {
        $data[] = fgetcsv($file, null, ';');
    }

    fclose($file);
    return $data;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, shame on me! I did everything on a wrong way. This must be the reason why I couldn't find any topic related to my problem :) Thank you very much, now everything works as it should be!
@Marc, I'd suggest to keep the declaration of $data. first, you are sure that it's initialized correctly, second, if there is no line in the file, the declaration never happens and the return value is null.

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.