php - 修复无效的 UTF8 字符
问题描述
我正在将一个 txt 文件导入到 sqlite 数据库中,然后使用 php 以 json 格式输出这些值
json_encode
失败,抱怨非法字符。我将它追踪到字符串中的两个重音字符terrains à bâtir
- 当我在 Sublime 中打开文件时,该字符串呈现良好,但在 Textedit 中,字符串显示为terrains ‡ b‚tir
有关文件及其内容的一些信息
file -i file.txt
告诉我text/plain; charset=us-ascii
mb_detect_encoding()
在一个有效的字符串上告诉我它是ASCII
mb_detect_encoding()
在一个无效的字符串上告诉我它是UTF-8
hexdump -C file.txt | grep terrains
将字符显示为点:
00a4eb30 7c 74 65 72 72 61 69 6e 73 20 e0 20 62 e2 74 69 ||terrains . b.ti|
cat file.txt | tail -c +1671338 | head -c 20
将字符显示为 �,它们以相同的方式出现在我的 sqlite GUI 中。ns � b�tir|11111|AAA
我知道可以使用 iconv 使用 TRANSLIT 或 IGNORE 选项来“修复”这个问题,但最终我得到的结果与预期的不同。
$encoding = mb_detect_encoding($row[2]);
if($encoding !== 'ASCII') {
$enc = mb_detect_encoding($row[2]);
$converted = iconv('UTF-8', 'ASCII//IGNORE', $row[2]);
print_r($converted);
}
使用IGNORE
(显然)输出terrains btir
和 TRANSLIT 方法抱怨iconv(): Detected an illegal character in input string
我的目标是使用 PHP 将这些字符恢复为正确的重音形式。我怎样才能做到这一点?我猜 hexdump 输出提供了一些线索,但我无法弄清楚哪些字节是有问题的字节或如何修复它们。
解决方案
推荐阅读
- c# - 为什么 Dart 将进程参数包装在 C# 没有的引号中?
- c - Does the following violates strict aliasing
- python - 等待上一个函数在Python中完成
- java - 如何在双向多对多映射中添加数据?(这不是添加数据的正常过程)
- javascript - jszip中的压缩文件比未压缩的内容大
- firefox-headless - Firefox 的无头屏幕截图不起作用
- node.js - GraphQL 查询结果中未返回的扩展
- php - 如何在 php 中集成 Paytm 以接受付款
- c - 在使用 gdb 的 VS-Code 调试 C 中忽略断点
- uipickerview - DarkMode 中的选取器文本颜色