dongxidui1227 2015-04-09 21:27
浏览 112

PHP:为什么iconv中的任何非拉丁字符给我“非法字符”错误?

For example:

$text = "пд";
echo 'Plain    : ', iconv("UTF-8", "us-ascii//TRANSLIT", $text), PHP_EOL;

outputs

Plain :
Notice: iconv() [function.iconv]: Detected an illegal character in input string in ...

I tried to add

setlocale(LC_CTYPE, 'en_US.UTF8');

but it doesn't matter...

  • 写回答

1条回答 默认 最新

  • duancuo1234 2015-04-09 21:32
    关注

    You need to make sure that your source file is actually saved in UTF-8, but not Windows-1251. Otherwise those characters won't be representing valid UTF-8 sequenses.

    Update:

    Right, the iconv //TRANSLATE seems to depend on locale. It may work correctly if you set it to the source language locale. So in your example, this would be some cyrillic locale I guess, but not 'en_US'.

    But in fact if you need transliteration just for one language, it's much more reliable to make a simple translation table youself:

    $trans = [
        'а' => 'a',
        'д' => 'd',
        'п' => 'p',
        ...
    ];
    $translit = str_replace(array_keys($trans), array_values($trans), $source_string);
    

    But if you need it to work for all/unknown languages, you will have to use something more complicated such as http://php.net/manual/en/class.transliterator.php

    评论

报告相同问题?

悬赏问题

  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo