Upload csv file and get datas php

Viewed 260

I am working on a website where there is an upload of a csv file on the server then we get this file to retrieve the data and make database insertions. The content of the csv file contains UTF8 accents (for example 'Cédric') With the current code, when we browse the file, Cédric becomes Cdric and if I open the uploaded file in Excel, it is well written Cédric

Here is the form code

<form id="upload" method="post" action="upload" enctype="multipart/form-data" accept-charset="utf-8">
                      <label>File</label>
                      <input id="upload" name="upload" type="file" value="">
                  </div>
              </div>
          </div>
      </div>
    </form>

Here is the upload function

            if (isset($_FILES['upload']) && $_FILES['upload']['error'] == 0) {
            $extension = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);

            if (strtolower($extension) !== 'csv') {
                $error['msg'] = 'Error';
            }

            if (move_uploaded_file($_FILES['upload']['tmp_name'], 'upload/' . $_FILES['upload']['name']))) {
                $error['msg'] = 'OK !';
            }
        }

And the data recovery code

$files = file('upload/' . $inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach (array_slice($files, 1, 5000) as $datas){
  $data = explode(';', $datas);
  var_dump($data[0]);
  die();
}

The var_dump($data[0]); show "Cdric"

How to do this to have "Cédric" please ?

1 Answers

Try to set the correct header information before print UTF

header('Content-Type: text/html; charset=utf-8');
$files = file('upload/' . $inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach (array_slice($files, 1, 5000) as $datas){
  $data = explode(';', $datas);
  echo $data[0];
  die();
}
Related