5

It seems that the delimiter of csv file edited and saved by OpenOffice Excel is ";" while microsoft office excel is ",", how should i write a program to parse the csv file no matter which delimiter it uses?

David
  • 2,691
  • 7
  • 38
  • 50
  • 1
    I think Microsoft would object to the trademark dilution involved in the use of 'Excel' to describe Openoffice spreadsheet. – pavium May 03 '11 at 06:12

3 Answers3

2

I'm using this function in one of my apps to determine which separator is used:

function get_separator( $csvstring, $fallback = ';') {
    $seps = array(';',',','|',"\t");
    $max = 0;
    $separator = false;
    foreach($seps as $sep){
        $count = substr_count($csvstring, $sep);
        if($count > $max){
            $separator = $sep;
            $max = $count;
        }
    }

    if($separator) return $separator;
    return $fallback;
}

It basically checks which separator occurs at most and returns it. It works without problems for about two years now

Xaver
  • 11,144
  • 13
  • 56
  • 91
1

Use SplFileObject::getCsvControl method. Example usage:

<?php
$csvFileObject = new SplFileObject($_FILES["csv"]["tmp_name"]);
list($delimiter, $enclosure) = $csvFileObject->getCsvControl();

$lines = fopen($_FILES["csv"]["tmp_name"], 'r');
if($lines) {
    while (($line = fgetcsv($lines, 4096, $delimiter, $enclosure)) !== false) {
        //do something
    }
}    

Reference: http://php.net/manual/en/splfileobject.getcsvcontrol.php

stz184
  • 363
  • 3
  • 12
0

fgetcsv() allows you to specify the delimiter as the third argument.

As for automatically detecting, there are some interesting answers for this question.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984