php - 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
我不想用 'é' 替换 'é' é
,我只想在我的文件中“硬编码”'é'。当我手动将 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()
有什么我想念的吗?
解决方案
推荐阅读
- java - 反转图表 - 试图提高节点效率
- wordpress - 即使高级设置>自定义css说“仅限专业版”,我能否以某种方式给出这个短代码自定义css?
- azure-active-directory - 如果清除本地状态,什么可以允许 Azure AD 应用程序访问而无需注销?
- django - 表单多选 - 无法分配 QuerySet,必须是用户实例
- python - 按下空格使图像显示 300 毫秒
- mysql - DATE_SUB(NOW(), INTERVAL 5 MINUTE) 在 PDO 语句中不起作用
- html - HTML 中的错误 - 红色结尾段落标签
- c# - 尝试使用 MainMenu 时 Visual Studio 2017 崩溃
- java - 很多库导致原因:java.lang.OutOfMemoryError
- go - 如何在 Go 中对 gRPC 服务进行单元测试