Home  >  Article  >  Backend Development  >  解决PHP导出CSV文中文乱码问题_PHP教程

解决PHP导出CSV文中文乱码问题_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:52:161525browse

解决PHP导出CSV文中文乱码问题

   csv文件可以使用excel打开并进行一些操作了,同时我们用php导入csv文件是非常的简单了,所以我们通常会使用php来导出csv了,但有时会碰到在使用Excel打开csv时出现乱码问题了,下面我们就来看解决办法。

  乱码情况

  写了一段导出 CSV 文件的代码,可以正常输出

  使用 CSV 和 TXT 程序打开文件是正常的,但是使用 Excel 打开文件就出现了中文乱码的问题(这就奇怪了, 为什么在 Excel 中会乱码呢?)

  通过查看编码发现,导出的 CSV 文件是 UTF-8 无BOM编码格式,而我们通常使用 UTF-8 编码格式 都是有 BOM 的。

  尝试着添加了 BOM 之后,中文乱码的问题有解决了。

  添加 BOM 到 CSV 文件中

  示例代码:

  $file = fopen($export_file_path, 'w');

  fwrite($file, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM

  foreach ($contens as $content) {

  fputcsv($file, $content);

  }

  fclose($file);

  另一种解决办法

  function down_file($filepath,$filename)

  {

  if(!file_exists($filepath))

  {

  echo "backup error ,download file no exist";

  exit();

  }

  ob_end_clean();

  header('Content-Type: application/download');

  header("Content-type: text/csv");

  header('Content-Disposition: attachment;filename="'.$filename.'"');

  header("Content-Encoding: binary");

  header("Content-Length:".filesize($filepath));

  header("Pragma: no-cache");

  header("Expires: 0");

  readfile($filepath);

  $e=ob_get_contents();

  ob_end_clean();

  }

  $fname='usersdata.csv';

  $handle=fopen($fname,'wb');

  $strUsersData =iconv('utf-8','gb2312',$strUsersData);//转换编码

  if(fwrite($handle,$strUsersData)==false){}

  fclose($handle);

  down_file($fname,'555.csv');

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1010442.htmlTechArticle解决PHP导出CSV文中文乱码问题 csv文件可以使用excel打开并进行一些操作了,同时我们用php导入csv文件是非常的简单了,所以我们通常会使用...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn