9 December 2015

Using PHP to read csv file is a common thing to do. Sadly there is no solid standard on delimiters, depends on fully from where you get your csv file. Usually simple csv exports are a bit different than what you get from xls to csv conversion. So I wrote a little function that detects csv delimiters of cells / fields. It counts predefined delimiter possibilites from the first row. Assumes that the highest occurred possible delimiter is the delimiter.

Source code viewer
  1. /**
  2.  * Detect delimiter of cells.
  3.  *
  4.  * @param string $name
  5.  * CSV file path.
  6.  *
  7.  * @return array
  8.  * Return detected delimiter.
  9.  */
  10. function detect_delimiter($name) {
  11. $delimiters = array(
  12. ';' => 0,
  13. ',' => 0,
  14. );
  15.  
  16. $handle = fopen($name, 'r');
  17. $first_line = fgets($handle);
  18. fclose($handle);
  19. foreach ($delimiters as $delimiter => &$count) {
  20. $count = count(str_getcsv($first_line, $delimiter));
  21. }
  22.  
  23. return array_search(max($delimiters), $delimiters);
  24. }
Programming Language: PHP