dousou2911 2019-04-29 22:41
浏览 692

在laravel中读取CSV文件时发出UTF-8,二进制数据和特殊字符

I am using League/CSV Laravel package to read and manipulate CSV file and save that CSV data into a database but I am facing some issues for some rows only which has some special characters like "45.6 ºF" while reading data from CSV.

I have searched a lot about this problem and found that we should use "UTF-8" or "utf8mb4" in the database collation and save that CSV in "utf8" also but it works only for all those special characters which are on the keyboard.

I want to use all type of special characters like "45.6 ºF" which are not on the keyboard also.

Currently, my code is reading CSV column data and convert it into binary data ' b"column value" ' It adds "b" with the string and converts that string into binary value for only those strings which have any special characters.

I have spent a lot of time but could not find any better solution to this problem. So please help me, I shall be very thankful to you.

 $reader = Reader::createFromPath(public_path().'/question.csv', 'r');
 $reader->setHeaderOffset(0);
 $records = $reader->getRecords();
 foreach ($records as $offset => $record) {
    $qs = Question::first();
    $qs->question =  $record['Question'];
    $qs->save();
 }

It is giving me this result after reading from CSV with "b".

array:2 [▼
  "ID" => "1"
  "Question" => b"Fahrenheit to Celsius (ºF to ºC) conversion calculator for temperature conversions with additional tables and formulas"
]

but it should be in the string format without "b" binary.

If I copy that string with special characters and assign it to the static variable, then it works fine and saves data into a database like this

$a="Fahrenheit to Celsius (ºF to ºC) conversion calculator for temperature conversions with additional tables and formulas";

$qs = Question::first();
$qs->question =  $a;
$qs->save();

After a lot of struggle, i have found the solution of this problem. I just added this line to code to convert it into utf8_encode before saving in the database.

$r = array_map("utf8_encode", $record);

Don't just copy paste the text from google to save in database because copy paste text and special characters don't work most of the time.

Thanks.

  • 写回答

2条回答

  • dtfo55908 2019-04-30 11:04
    关注

    I have found a solution to this problem. below line of code fixed my issue $r = array_map("utf8_encode", $record); We just need to convert into utf8_encode before saving into database.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器