0

I'm not able to read a tabulator seperarated csv file (and yes, i know its csv and no tsv and the c is for tabulator...) with php and seperate it right. When i give out my imported Data with echo or readfile all the tabulators are replaced by a space and i can't use space as a sperator.

Actually i'm a bit confused that this problem is not very common when i use Google, so maybe i'm the problem...

The Problem exists with XAMPP v3.2.3 and PHP Version 7.3.5

$tempFile = fopen($tempFilePath, "r");
        $uploadData = fread($tempFile, filesize($tempFilePath));
        fclose($tempFile);

        echo $uploadData;


        $uploadData =   str_replace('"','',$uploadData);    
        $uploadData = str_replace('\r\n','\n',$uploadData);
        $uploadData = str_replace('\r','\n',$uploadData);
        $uploadData = str_replace(';',',',$uploadData);
        $uploadData = str_replace('\t',',',$uploadData); //Here i'm trying to replace the tabulator with a colon to work with it afterwards
reinmanu
  • 23
  • 3

2 Answers2

0

When reading a CSV file in PHP, it is best to use the fgetcsv function. With it you can specify the deliminator of the file. The function will output a row of the file. Your deliminator should be "\t".

ARubiksCube
  • 146
  • 8
  • The Problem actually is that more people are using it, and i can't specify the systems and configurations. So i would like to make it possible to use it with colon, semicolon and tabulator as seperator. And yes, i hate Excel for this... – reinmanu Jun 18 '19 at 14:11
  • Take a look at this post with a very similar issue: [Link](https://stackoverflow.com/questions/1372223/reading-from-comma-or-tab-delimited-text-file) – ARubiksCube Jun 18 '19 at 14:14
0

You should use fgetcsv function which already has functionality to read tsv.

Like this:

$uploadData = [];
if (($handle = fopen("test.csv", "r")) !== false) {
    while (($data = fgetcsv($handle, 0, "\t")) !== false) {
        $uploadData[] = $data;
    }
    fclose($handle);
}

If you want to convert tsv to csv you can use inverse function fputcsv:

$fh = fopen('file.csv');
foreach ($uploadData as $datum) {
    fputcsv($fh, $datum);
}
fclose($fh);

If you want automatically detect csv delimiter maybe this article can help you.

marv255
  • 808
  • 6
  • 19