PHP 如何使用 fputcsv 函数将数组转换为 csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14809133/
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 08:00:54 来源:igfitidea点击:
PHP How to convert array into csv using fputcsv function
提问by Sami El Hilali
please I have the following array :
请我有以下数组:
array(3) {
[0]=>
array(2) {
[0]=>
string(6) "lkjhgj"
[1]=>
string(16) "[email protected]"
}
[1]=>
array(2) {
[0]=>
string(5) "hgjk,"
[1]=>
string(18) "[email protected]"
}
[2]=>
array(2) {
[0]=>
string(9) "dddd ffff"
[1]=>
string(13) "[email protected]"
}
}
I want to put it into a csv file, so I've tried :
我想把它放到一个 csv 文件中,所以我试过:
$fichier = 'file.csv';
$fp = fopen($fichier, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$fichier);
But when I download the file I found it empty !
但是当我下载文件时,我发现它是空的!
Please masters any idea ? Thanks in advance
请高手有什么想法吗?提前致谢
PS : Permissions are 777
PS:权限是777
回答by Suhel Meman
$fichier = 'file.csv';
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$fichier\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
exit();
回答by Mamoon Rashid
If you are saving array in session and issues of encoded characters.
如果您在会话中保存数组和编码字符的问题。
session_start();
$fp = fopen($_SESSION['CSV']['type'].'.csv', 'w');
foreach ($_SESSION['CSV'] as $fields) {
$val1 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[0], ENT_QUOTES | ENT_XML1, 'UTF-8')));
$val2 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[1], ENT_QUOTES | ENT_XML1, 'UTF-8')));
$val3 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[2], ENT_QUOTES | ENT_XML1, 'UTF-8')));
fputcsv($fp, array($val1,$val2,$val3,$val4,$val5));
}
fclose($fp);

