首页 > 解决方案 > 修复无效的 UTF8 字符

问题描述

我正在将一个 txt 文件导入到 sqlite 数据库中,然后使用 php 以 json 格式输出这些值

json_encode失败,抱怨非法字符。我将它追踪到字符串中的两个重音字符terrains à bâtir- 当我在 Sublime 中打开文件时,该字符串呈现良好,但在 Textedit 中,字符串显示为terrains ‡ b‚tir

有关文件及其内容的一些信息

00a4eb30 7c 74 65 72 72 61 69 6e 73 20 e0 20 62 e2 74 69 ||terrains . b.ti|

我知道可以使用 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 输出提供了一些线索,但我无法弄清楚哪些字节是有问题的字节或如何修复它们。

标签: phpcharacter-encodingiconv

解决方案


推荐阅读