开发者

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

开发者 https://www.devze.com 2023-03-02 01:31 出处:网络
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

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?


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


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


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消