Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Processing CSV file separated by semicolon

Tags:

php

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.

like image 235
Kiss Koppány Avatar asked Apr 07 '15 08:04

Kiss Koppány


People also ask

Can CSV file be separated by semicolons?

Data export CSV files from Salesforce and other sources may sometimes contain semicolons as a list separator. When you upload files, Salesforce only accepts commas (,) as a default separator for CSV file. To prevent issues during data import, semicolons should be replaced with commas.

How do I process a CSV file in php?

PHP fgetcsv() Function$file = fopen("contacts. csv","r"); print_r(fgetcsv($file)); fclose($file);

What is semicolon in CSV?

Depending on your Excel's regional setting, your default delimiter/separator may either be using semicolons (;) or commas (,) to separate items in a CSV file.

How do I read the first line of a CSV file in php?

php $row = 1; if (($handle = fopen("ab. csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] .


1 Answers

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;
}
like image 184
Marc Avatar answered Nov 11 '22 18:11

Marc