(PHP) Allow any delimiter in CSV file

By | May 31, 2015

In a Laravel app I made the users would upload CSV files. The problem was that fgetcsv only allows a single delimiter character, and it needs to be defined.

The problem with that is that when a user exports a CSV from MS Excel – it could end up using a wide array of delimiters depending on the locality settings in windows.  It kind of sucks that MS won’t let the user choose this on export, but that’s how it is.

So I solved it the quick and easy way, by making a function that simply replaces any delimiter character to  my desired delimiter. (Note that the tab character is in double quotes, since it won’t be interpreted as tab otherwise):

    /**
     * Will replace a number of CSV delimiters to one specific character
     * @param $file     CSV file
     */
    private function replaceDelimiters($file)
    {
        // Delimiters to be replaced: pipe, comma, semicolon, caret, tabs
        $delimiters = array('|', ';', '^', "\t");
        $delimiter = ',';

        $str = file_get_contents($file);
        $str = str_replace($delimiters, $delimiter, $str);
        file_put_contents($file, $str);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *