php 在php中使用fputcsv将utf-8字符写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21988581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:36:18  来源:igfitidea点击:

write utf-8 characters to file with fputcsv in php

phpencodingcharacter-encoding

提问by Yuseferi

I want to try write Persian character in CSV file in PHP, I am using fputcsvfunction but how can write UTF-8 character to CSV file with fputcsv?

我想尝试在 PHP 中的 CSV 文件中写入波斯字符,我正在使用fputcsv函数但是如何将 UTF-8 字符写入 CSV 文件fputcsv

Part of my code:

我的部分代码:

$df = fopen($filepath, 'w');
fputcsv($df, array($coupon->code, $discount->label));

回答by Hardy

Try this:

尝试这个:

$df = fopen($filepath, 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($df, array($coupon->code, $discount->label));

the line fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));writes file header for correct encoding.

该行fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));写入文件头以进行正确编码。

回答by robssanches

Try this also:

也试试这个:

$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);

回答by Syno

If you want make a UTF-8 file for excel, use this simple solution:

如果你想为 excel 制作一个 UTF-8 文件,使用这个简单的解决方案:

$fp = fopen($filename, 'w');

//add BOM to fix UTF-8 in Excel 
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

See the original answer hereon the official PHP page.

看到原来答案在这里正式PHP页面上。