Home > Software design >  PHP open CSV with ; and make a array with first array items as column name
PHP open CSV with ; and make a array with first array items as column name

Time:10-07

I have write a code to read the csv file, but this code only works with a csv , (comma) seperate. I want to read a file that is ; (dot-comma) seperate. This code works good for comma seperate only:

 $csv = array_map("str_getcsv", file("activeproducts_per_customer.csv", FILE_SKIP_EMPTY_LINES));
        $keys = array_shift($csv);

        // Make the CSV as a array
        foreach ($csv as $i => $row) {
            $csv[$i] = array_combine($keys, $row);
        }

        // echo "<pre>";
        // print_r($csv);
        // echo "</pre>";
        return $csv;

CodePudding user response:

you should try using this

phpspreadsheet

it's easy to use and there is a lot of tutorials there can help you, you can watch this : phpspreadsheet toturial

I hope it solves your problem

CodePudding user response:

I'm just wondering why you didn't use fgetcsv. You can use this and define separator as you like.

Ref: https://www.php.net/manual/en/function.fgetcsv.php

For your case:

$csv = [];
if (($handle = fopen("activeproducts_per_customer.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
        $csv[] = $data;
    }
    fclose($handle);
}

return $csv;

You may increase the limit as you want.

CodePudding user response:

Try this code for set delimiter

 $csv = array_map(function($v){return str_getcsv($v, ";");}, file("activeproducts_per_customer.csv", FILE_SKIP_EMPTY_LINES));
    $keys = array_shift($csv);

    // Make the CSV as a array
    foreach ($csv as $i => $row) {
        $csv[$i] = array_combine($keys, $row);
    }

    // echo "<pre>";
    // print_r($csv);
    // echo "</pre>";
    return $csv;

CodePudding user response:

str_getcsv accepts separator as second parameter.

This solution might help

  • Related