dqeznd1697
2015-03-03 17:34
浏览 183
已采纳

将csv文件处理为UTF-8

Trying to figure out how to process a csv file with UTF encoding. Tried multiple ways like adding this utf8_encode() and with this in the header:

header('Content-Type: text/html; charset=UTF-8');

But nothing seems to work.

The code is:

<?php
include 'head.php';
$csv = array_map("str_getcsv", file("translations/dk.csv"));
foreach ($csv as $line){
     $translate["dk"][ $line[0] ] = $line[1];
}if ($line[1] != NULL){
    $line[0] = $line[1];
}
echo $line[0];
fclose($csv);
?>

How to I echo the output with UTF-8 encoding?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhui1630 2015-03-03 17:43
    已采纳

    When you would display it in a browser you should use valid html and set the meta charset to utf8 too:

    <?php
    include 'head.php';
    ?>
    <!DOCTYPE html>
    <html lang="dk">
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
    <?php
    
    $csv = array_map("str_getcsv", file("translations/dk.csv"));
    foreach ($csv as $line){
         $translate["dk"][ $line[0] ] = $line[1];
    }if ($line[1] != NULL){
        $line[0] = $line[1];
    }
    echo $line[0];
    fclose($csv);
    ?>
    </body>
    </html>
    

    Or using text/plain instead of text/html can help:

    header('Content-Type: text/plain; charset=UTF-8');
    

    Hope that helps.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douju2053 2015-03-03 17:43

    Based on what you described it looks like the file isn't in UTF-8 format, its probably in ISO-8859-1 but you are trying to display as if it was in UTF-8, hence why you see strange blocky symbols.

    You have two options, you can convert the file entries to UTF-8 with:

    foreach ($csv as $line)
        $translate["dk"][$line[0]] = utf8_encode($line[1]);
    

    Or declare the file real encoding to the browser so it will display correctly:

    header('Content-Type: text/html; charset=ISO-8859-1');
    

    Since W3C recommends UTF-8 as default encoding for web, the first option should be prefered.

    Alternatively, you can convert the entire file to UTF-8 using your favorite text editor and save it that way, so you don't have to convert it to UTF-8 every time.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题