Kiss Koppány
Kiss Koppány

Reputation: 950

PHP Processing CSV file separated by semicolon

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.

Upvotes: 12

Views: 15118

Answers (1)

Marc
Marc

Reputation: 3709

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;
}

Upvotes: 20

Related Questions