Tag Archives: csv

How to parse a csv file in php when the delimiter is unknown

There are plenty of MS Excel alternatives out there – OpenOffice, LibreOffice, Kingsoft, Google Spreadsheets and many more. The problem is that CSV files created by different softwares may vary (, or ; to name a few options). If you need to process CSV files exported from different systems and software and handle the delimiter automatically, you can benefit from using 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