utf8_encode does not produce right result

2019-06-04 01:16发布

问题:

My problem is the following:

I store an array, which has keys like "e", "f", etc. At some point, I have to get the value of the key. This works well. But if I want to store "í", "é", etc. as the keys, it won't produce the right result (results in �). My page has to be in UTF-8. Looking up the problem, I found out that utf8_encode should help my problem. It didn't: although it produced a more-readable character, it still totally differed from what I want. If important, phpinfo gives:

Directive   Local Value Master Value
iconv.input_encoding    ISO-8859-1  ISO-8859-1
iconv.internal_encoding ISO-8859-1  ISO-8859-1
iconv.output_encoding   ISO-8859-1  ISO-8859-1

What could help the problem?

Edit: I think that array keys make some data loss. Is it true? If yes, how to prevent?

Edit2: Solutions I've tried so far: get the array key value - failed; make an array with same keys but a values of utf-8 characters: failed; utf8_encode failed; [tried with both] iconv_set_encoding: failed; ini_set failed; mb_internal_encoding failed. All returned with either à or �.

回答1:

I've put together some solutions and finally it works.

What I've done is the following: First, I've put together all solutions with adding this line:

ini_set('default_charset', 'UTF-8');
iconv_set_encoding("input_encoding", "UTF-8");
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "UTF-8");
mb_internal_encoding("UTF-8");

This did not work.

I looked at all the links, the utf8_encode - utf8_decode method didn't work. Then I took a look at the functions, I found the mbstring, so I replaced every string function with its mbstring equivalent.

This worked fine. Then, I figured out that mb_internal_encoding("UTF-8"); is enough. So now it works. Thanks for all the suggestions!



回答2:

Try adding this line at the top of all scripts that'll have to deal with UTF-8 data:

mb_internal_encoding("UTF-8");

or even better, edit the internal encoding in your php.ini file.



回答3:

Try setting the default_charset directive:

ini_set('default_charset', 'UTF-8');

This sets the character encoding which is sent to the browser in the Content-Type header.