首页 > 解决方案 > CSV windows excel 特殊符号编码

问题描述

我在 CSV 文件中显示特殊字符时遇到问题。它工作正常,除了在 windows excel 中。我尝试添加 windows-1252 编码,我猜它应该正确显示特殊字符,但事实并非如此。谁能告诉我我错过了什么?我的代码是:

$file = tempnam(sys_get_temp_dir(), 'mycsv');
 $fh = fopen($file, 'w');

 $currencyOption = $account->team->user->getOption('accounting', 'currency');
 $currency = config('currencies.'.$currencyOption);

   if($currency)
   {
       $symbol = '€';//$currency['format'];
       $symbol = str_replace('%s ', '', $symbol);
       $symbol = str_replace(' %s', '', $symbol);
       $encoding = mb_detect_encoding($symbol);
       $symbol = iconv($encoding, "Windows-1252", $symbol);
   }

 $groups = [];

 foreach($account->fees as $fee)
 {
   if(!isset($groups[$fee->group]))
   {
     $groups[$fee->group] = $fee->name . " ($symbol)";
   }
 }

 fputcsv($fh, array_merge([___('Player')], $groups, [___('Total') . " ($symbol)"]));

 foreach($account->players as $player) {
   $row = [$player->name];
   foreach($groups as $groupId => $groupName)
   {
    $val = $account->fees->where('player_id', $player->id)->where('group', $groupId)->first();
    $row[] = $val ? $val->value : '0';
   }
   $row[] = $player->credit;
   fputcsv($fh, $row);
 }

 $row = [''];
 foreach($groups as $groupId => $groupName)
 {
   $row[] = '';
 }
 $row[] = $account->balance;
 fputcsv($fh, $row);
 fclose($fh);

   return response()->download($file, 'account.csv', [
       'Content-Encoding' => 'Windows-1252',
       'Content-Type' => 'text/csv; charset=Windows-1252',
       'Content-Disposition' => "attachment; filename='account.csv'",
   ]);

标签: phplaravelcsvencodingspecial-characters

解决方案


推荐阅读