How should I parse a csv file in php when the delimiter changes?

It seems that the csv file separator edited and saved by OpenOffice Excel is ";" while Microsoft Office Excel is ",", how do I write a program to parse a csv file no matter what separator it uses?

+5
source share
3 answers

I use this function in one of my applications to determine which delimiter 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 delimiter occurs in most cases and returns it. He works without problems for about two years.

+2
source

SplFileObject:: getCsvControl. :

<?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
    }
}    

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

+1

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

Regarding automatic detection, there are some interesting answers for this question .

0
source

All Articles