首页 > 解决方案 > csv 到 json,无法正确编码输出

问题描述

我有以下格式的 csv 文件:

// file: nl.csv
One;Eén
Two;Twee
Three;Drie

该文件是用 Excel 创建的。

使用 PHP,我想从这个 csv 文件创建一个新的 js 文件,样式如下:

// file: nl.js
export const nl = {
    One: "Eén",
    Two: "Twee",
    Three: "Drie"
}

到目前为止一切顺利,我设法创建了一个 PHP 函数来读取 csv 文件并将其解析为 js 文件:

<?php
$language = 'nl';
$csv = file($file.'.csv');
$data = array();
foreach($cvs as $line){
    $data[] = str_getcsv($line, ';');
}
$handle = fopen($language.'.js', 'w');
fwrite($handle, "export const {$language} = {\n");
foreach($data as $line){
    $key = $line[0];
    $value = $line[1];
    fwrite($handle, "\t{$key}: \"{$value}\",\n");
}
fwrite($handle, "}");
fclose($handle);
?>

问题在于编码:在第一行,文本中有一个“é”。这没有正确转换,我得到一个带有白色问号的黑色方块。

当我检查每一行的编码时,我得到以下输出:

// function
mb_detect_encoding($line)

// output
UTF-8 // first line with 'é'
ASCII // second line
ASCII // third line

我不想用 'é' 替换 'é' &eacute;,我只想在我的文件中“硬编码”'é'。当我手动将 json 文件中的所有黑色方块更改为“é”时,它可以工作。

到目前为止我做了什么:

// adding htmlspeciarchars
$data[] = str_getcsv(htmlspecialchars($line), ';');
// the first line does not get output, the other lines do

// adding htmlentities
$data[] = str_getcsv(htmlentities($line), ';');
// same as with htmlspecialchars()

有什么我想念的吗?

标签: phpjsoncsv

解决方案


推荐阅读