【发布时间】:2020-07-13 15:32:36
【问题描述】:
我有一个包含姓名和日期列表的巨大 csv。我需要将其中的一个子集放入给定月份的 PHP 结构中。因此,我运行 CSV 并过滤那些我想要月份的行,将名称提交到列表,然后使用 json_encode 将该列表保存到文件中。
我每个月都这样做一次,总共 12 次,因为我只需要一年。
我从第 1 个月到第 7 个月没有问题。现在第 8 个月失败了。列表已生成,但没有存储任何内容,因为 json_encode 失败。
调用 json_last_error_msg() 会提供消息 Malformed UTF-8 characters。
我通过这样做来阅读 CSV
if (($handle = fopen($in_csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$line++;
$data = array_map("utf8_encode", $data); // <- This was added after the first failure. But I have tried without it
// ... do stuff with data and save the name and last name to a struct.
}
fclose($handle);
}
// At the end I do
$fid = fopen("filename","w");
fwrite($fid,json_encode($output));
echo "JSON ENCODE RESULT: " . json_last_error_msg() . "\n";
fclose($fid);
我真的需要这个来工作。 JSON 有什么方法可以告诉我它不喜欢什么,以便我可以删除或更正它?
【问题讨论】:
-
你有什么错误吗?根据the docs,您可以通过将选项作为第二个参数传递给PHP 来告诉
JSON_THROW_ON_ERROR,然后找出编码失败的原因。 -
一个疯狂的猜测是你需要做 [
mb_convert_encoding] (php.net/manual/en/function.mb-convert-encoding.php) 你可以尝试做一些事情mb_convert_encoding($string, 'UTF-8', 'UTF-8');西里尔语言通常是这种情况 -
我们无法复制问题,因为我们什么都不知道。始终包含错误以及当它不起作用时变量所包含的内容。
-
@JimWright 是的,失败的原因是“格式错误的 UTF-8 字符”问题中的原因。但是我不知道哪些应该是畸形的,我不知道如何修复它。
-
@Andreas 问题出在问题上,正如我所说,该变量由超过 500 个名称的文本字符串组成。我应该如何提供变量内容?