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?
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.
精彩评论