search
Homephp教程php手册PHP生成CSV文件用Excel打开乱码问题

PHP生成CSV文件用Excel打开乱码问题

Jun 13, 2016 am 09:46 AM
csvexcelphponeWhyGarbled charactersclassmateOpendocumenthavegenerateusequestion

今天有一同学问我为什么PHP生成CSV文件用Excel打开会出现乱码呢,下面小编来给大家找了一些常见的办法,希望此方法对各位朋友会有所帮助。

百度查证后得知

PHP生成UTF-8编码的CSV文件用Excel打开中文显示乱码,是由于输出的CSV文件中没有BOM。

我们只要简单处理一下即可

那么如何在PHP中输出BOM呢?

在所有内容输出之前

 代码如下 复制代码

print(chr(0xEF).chr(0xBB).chr(0xBF));


例.php生成csv时我们可以这样

 代码如下 复制代码

$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");
 
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
 
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
$items_data=array(
'0'=>array('title'=>'test test test1'),
'1'=>array('title'=>'test test test2'),
'2'=>array('title'=>'test test test3')
)
print(chr(0xEF).chr(0xBB).chr(0xBF));//设置utf-8 + bom ,处理汉字显示的乱码
echo array2csv($items_data);
 
function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}
?>

还有一种办法就是使用Office

打开Microsoft Office 2010 Excel,数据-自文本,如图:

导入此csv格式文件,同样要求选择编码,如图:

  这里选择UTF-8,打开后,发现乱码消除,如图:

  补:UTF-8是在互联网上使用最广的一种unicode编码的实现方式。UTF-8最大的一个特点,就是它是一种变长的编码方式。它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!