search
Homephp教程php手册解决PHP导出CSV文中文乱码问题

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

Jun 13, 2016 am 09:02 AM
cscsvphpChineseGarbled charactersExportsolvequestion

解决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');

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools