mercredi 28 février 2018

How to make csv import work on both mac and windows

I simply would like to import this text from a csv file into a laravel php script that parses it:

store_id,ref,priority,tagline
10,confuscian,5,confuscian says

when I send this on a mac machine on chrome, the body of the csv appears like this:

enter image description here

enter image description here

so you can see that a \n is added:

{"csv":"store_id,ref,priority,tagline\n10,confuscian,5,confuscian says"}

however, when I add the same csv from windows, it appears like so:

{"csv":"store_id,ref,priority,tagline 10,confuscian,5,confuscian says"}

the script that reads this filters out the \r\n different OS problem like so:

    $file = storage_path('batch_update.csv');
    // replace new line characters for mac/win/linux
    $str = preg_replace('/(\r\n|\r|\n)+/', "\n", $this->data);
    file_put_contents($file, $str); 

    $this->data = $this->csvToArray($file);

    if (!$this->data || !$this->checkForRequiredColumns()) {
        return false;
    }

the problem is that in windows, the \n doesn't even show up! which confuses the csvToArray script:

trait CsvHelpers { private function csvToArray($filename) { if (!file_exists($filename) || !is_readable($filename)) { return false; }

    $header = null;
    $data   = array();
    if (($handle = fopen($filename, 'r')) !== false) {
        while (($row = fgetcsv($handle, 1000, ',')) !== false) {
            $row = array_map('trim', $row);
            if (!$header) {
                $header = $row;
            } else {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

question

how do i make it so that when i export a csv in windows, every line ends in \n?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2oFgcsH
via IFTTT

Aucun commentaire:

Enregistrer un commentaire