mb_convert_encoding issues

29,056

You've not actually converted your string. Rather, the call to mb_convert_encoding did not assume that the original string was in UTF-8. The string before the call was a byte sequence that could have been ISO-8859-1 already (and would have represented items differently). You can see this is the case by, rather than calling the mb_detect_encoding, using bin2hex on the string and seeing the byte-sequence after the conversion call. You'll see the byte sequence was unchanged.

To get the conversion to work, you need to tell it (in this case) the original encoding. Use:

mb_convert_encoding($str, 'ISO-8859-1','utf-8');

If you examine the byte-sequence after this you'll see conversion has taken place.

Share:
29,056
brasimon
Author by

brasimon

Updated on August 05, 2020

Comments

  • brasimon
    brasimon almost 4 years

    I have some issues with the PHP function mb_detect_encoding. I can't convert it to ISO-8859-1. Any help?

    Code:

    $str = "åäö";
    $encoding = mb_detect_encoding($str);
    echo $encoding;
                
    $encoding = mb_detect_encoding(mb_convert_encoding($str, "ISO-8859-1"));
    echo $encoding;
    

    Output:

    UTF-8

    UTF-8

    Updated, solution:

    I updated mb_detect_order to array('UTF-8', 'ISO-8859-1') and it worked.