duangao7133 2013-07-26 14:52
浏览 39
已采纳

UTF-8 htmlentities和fgetcsv

I am having issues converting my special characters to htmlentities after importing my csv file.

Here's the revelant code:

setlocale(LC_ALL, 'fr_FR.utf8');

if (empty($errors) && ($handle = fopen($_FILES["file"]["tmp_name"], "r")) !== FALSE) {
    $data = array();
    while (($rawdata = fgetcsv($handle, 0, $_POST["delimiter"])) !== FALSE) {
         for ($i=0; $i < count($rawdata); $i++) {
              $data[$i][] = htmlentities(trim($rawdata[$i]), ENT_QUOTES, "UTF-8");
         }
    }
    fclose($handle);
}

What happens though, is that any cells with a special character in it (such as ™) simply get removed / return as empty.

I'm using PHP version 5.3.13

I have tried setting my locale and tried putenv, but this doesn't change anything. I have also tried setting my machine's locale settings before making the csv. The csv itself is created from an Excel file.

I have checked my csv encoding, and it seems correctly to be UTF-8 without BOM (checked in Notepad++). mb_detect_encoding() also returns UTF-8.

When I change to ENT_IGNORE, it simply strips the TM symbol from my string. I have tried different encoding types such as ISO-8859-15 with no avail.

str_replace("™", "%99", $row) just ignores the TM symbols and leaves them how they were.

I've found that a lot of people have issues with fgetcsv() and encoding / special characters, and most of them refer to using a different method such as fgets(). Unfortunately I haven't been able to get those other methods to work either because I cannot explode on newline since some of the cells may include newlines in their content. I will accept a different method as answer as well if I can get it to work.

  • 写回答

1条回答 默认 最新

  • douwen5833 2013-08-09 13:55
    关注

    Using iconv() on my rawdata in the for loop solved my issue:

    $data[$i][] = htmlentities(iconv("cp1252", "utf-8", trim($rawdata[$i])), ENT_IGNORE, "UTF-8");
    

    Thank you @Leigh, Wrikken and DaveRando from the PHP chat ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么