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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog