title: Can't encode CSV file in UTF8 with PHP
body: <p>I've been trying, for some time now, to export a properly encoded and formated CSV file with PHP. But it's just not working. I've tried every tip in every CSV/PHP related thread on SOF, I've checked that the data in my database is UTF-8, it is. I've tried stuff like utf8_encode() on the whole CSV-line, I've checked that the actual PHP file is encoded in UTF-8, but still no success. When I run the file on <a href="http://csvlint.io/" rel="nofollow noreferrer">http://csvlint.io/</a> I just get:</p>
  
  <blockquote>
    <p>Your CSV appears to be encoded in ASCII-8BIT. We recommend you use UTF-8.</p>
  </blockquote>
  
  <p>But I can't find a trace of any other encoding than UTF-8 anywhere in my code..
  Basically this is my code:</p>
  
  <p>First, I put all my CSV-rows in an array, then do this:</p>
  
  <pre><code>if (count($array) == 0)
  {
      return NULL;
  }
  ob_start();
  $df = fopen("php://output", 'w');
  $csv = utf8_encode("header1|header2|header3|header4|header5|header6|header7\r\n");
  foreach($array as $line) {
      $csv .= $line . "\r\n";
  }
  setlocale(LC_ALL, 'sv_SE', "swedish");
  fwrite($df, "\xEF\xBB\xBF".$csv);
  fclose($df);
  return ob_get_clean();
  </code></pre>
  
  <p>And these are the headers sent:</p>
  
  <pre><code>$now = gmdate("D, d M Y H:i:s");
  header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
  header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
  header("Last-Modified: {$now} GMT");
  header("Content-Encoding: UTF-8");
  header("Content-Type: text/csv; charset=UTF-8");
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");
  header("Content-Disposition: attachment;filename={$filename}");
  header("Content-Transfer-Encoding: binary");
  </code></pre>
  
  <p>Any ideas?</p>