David
David

Reputation: 2721

how should i parse the csv file in php when the delimiter varies?

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?

Upvotes: 5

Views: 4165

Answers (3)

Xaver
Xaver

Reputation: 11652

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

Upvotes: 2

stz184
stz184

Reputation: 383

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

Upvotes: 1

alex
alex

Reputation: 490143

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

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

Upvotes: 0

Related Questions