iconv() – how to detect offending character?

我只是一个虾纸丫 提交于 2019-12-11 15:21:54

问题


I use iconv() to convert CSV data from UTF-8 to Windows-1252.

$converted = iconv("UTF-8", "Windows-1252", $csvData);

In some cases, iconv() failed quietly, returning false.

I also tried using //TRANSLIT but `iconv()´ returns false here as well.

When i add the //IGNORE statement to the target charset, the conversion succeeds, but that means one or more character(s) got lost.

I can stick to //IGNORE but i would like to find out which character(s) are causing the problem.

How can i do this?


回答1:


It was bad idea to work with string as char array (see question comments) because php string type

Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

So we can use mb_substr for utf-8 and work with symbols not bytes

error_reporting('E_ALL & !E_NOTICE');
$yourString = "test bad ☺ string";
$convertString = '';
$badChars = [];

if (iconv("UTF-8", "Windows-1252", $yourString) === false) {       
    for($i = 0, $stringLength = mb_strlen($yourString); $i < $stringLength; $i++) {
        $char = mb_substr($yourString, $i, 1);
        $convertChar = iconv("UTF-8", "Windows-1252", $char);

        if ($convertChar === false) {
            $badChars[$i] = $char;
        } else {
            $convertString .= $convertChar;
        }   
    }
} else {
    $convertString = iconv("UTF-8", "Windows-1252", $yourString);
}

var_dump($badChars, $convertString);

Result array(1) { [9]=> string(3) "☺" } string(16) "test bad string"

P.S. The next time I will give a more detailed answer with the code. My mistake



来源:https://stackoverflow.com/questions/47221756/iconv-how-to-detect-offending-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!