Question: I Want To Contribute - Delimiter Auto For Csv

I Want To Contribute - Delimiter Auto For Csv

Delimiter in CSV (Auto) There is a way (i took from internet for a project) to detect a delimiter in a CSV (for the funcionalities that you have in SMA where take a CSV file) This because d

JC

Jorge Cadena

Asked
Delimiter in CSV (Auto)
There is a way (i took from internet for a project) to detect a delimiter in a CSV (for the funcionalities that you have in SMA where take a CSV file)

This because depending of the configuration in EXCEL the delimiter change... sometimes is a "," or ";" and you know ...

To include in Site.php

public function detectDelimiter($csvFile)
{
$delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];
$handle = fopen($this->digital_upload_path . $csvFile, 'r');
$firstLine = fgets($handle);
fclose($handle);
foreach ($delimiters as $delimiter => &$count) {
$count = count(str_getcsv($firstLine, $delimiter));
}
return array_search(max($delimiters), $delimiters);
}

To invoke from any php that upload a file (CSV) in my case in Purchase.php and others...

$delimiter_auto = $this->site->detectDelimiter($csv);
....
while (($row = fgetcsv($handle, 1000, $delimiter_auto)) !== false ) {

I hope this can help you
  • MS

    Mian Saleem

    Answered
    Hello, thank you very much for sharing the snippet. I will check in next update about this.
  • Login to Reply