2

I would like to create a CSV document with a tab delimiter. I've tried a lot of things and searched all over the internet but there isn't a single site with a working solutions. This is the script I'm using right now, but it is exporting without a tab delimiter

    $data[] = array("item 1", "item 2");
    $data[] = array("item 3", "item 4");
    $export = fopen("/export/test.csv", "w");
    foreach ($data as $row) {
      fputcsv($export, $row, "\t");
    }
    fclose($export);

I've also tried different other things instead of \t like chr(9) but nothing worked. Any solutions for this problem?

Stefan
  • 249
  • 5
  • 17
  • In what way doesn't this solution work? What is going wrong? How are you checking the result? http://ideone.com/41ei6Z – Mark Baker Nov 07 '14 at 16:43
  • I save the data to a .csv document; test.csv. In the ideone.com example it is indeed working, so probably the error occurs while the data is saved to the .csv document? – Stefan Nov 07 '14 at 16:48
  • PHP doesn't care whether the filestream is php://output or a file on disk. You still haven't answered the questions I posted? What are you actually getting in your csv file? Use a text editor to check. – Mark Baker Nov 07 '14 at 16:49
  • Ok, you are right. The csv file is indeed with tabs but the tabs aren't visible in Excel 2011 for mac. Thanks for your help! – Stefan Nov 07 '14 at 16:59
  • 5
    The separator when MS Excel imports a csv file is local-specific to that version of MS Excel; but you can normally force it by writing a `sep` line before the actual csv content: `fwrite($export, "sep=\t".PHP_EOL);` – Mark Baker Nov 07 '14 at 17:09
  • Could it be combined with fputcsv? Since fputcsv($export, $row, "sep=\t".PHP_EOL); isn't working for me? – Stefan Nov 07 '14 at 18:42
  • 1
    I've found another solutions which is working pretty well: fputcsv($export, $row, ';', '"'); – Stefan Nov 07 '14 at 19:43

1 Answers1

4

Was searching for a solution to the same problem. Saw the solution in the comments by Mark Baker

Use fwrite($export, "sep=\t".PHP_EOL); before writing any contents to the file.

NealVDV
  • 2,302
  • 3
  • 26
  • 51