So I have an array of strings, and all of the strings are using the system default ANSI encoding and were pulled from a SQL database. So there are 256 different possible character byte values (single byte encoding).
Is there a way I can get json_encode()
to work and display these characters instead of having to use utf8_encode()
on all of my strings and ending up with stuff like u0082
?
Or is that the standard for JSON?
If you have an ANSI encoded string, using
utf8_encode()
is the wrong function to deal with this. You need to properly convert it from ANSI to UTF-8 first. That will certainly reduce the number of Unicode escape sequences likeu0082
from the json output, but technically these sequences are valid for json, you must not fear them.Converting ANSI to UTF-8 with PHP
json_encode
works withUTF-8
encoded strings only. If you need to create validjson
successfully from anANSI
encoded string, you need to re-encode/convert it toUTF-8
first. Thenjson_encode
will just work as documented.To convert an encoding from
ANSI
(more correctly I assume you have aWindows-1252
encoded string, which is popular but wrongly referred to asANSI
) toUTF-8
you can make use of themb_convert_encoding()
function:Another function in PHP that can convert the encoding / charset of a string is called
iconv
based on libiconv. You can use it as well:Note on utf8_encode()
utf8_encode()
does only work forLatin-1
, not forANSI
. So you will destroy part of your characters inside that string when you run it through that function.Related: What is ANSI format?
For a more fine-grained control of what
json_encode()
returns, see the list of predifined constants (PHP version dependent, incl. PHP 5.4, some constants remain undocumented and are available in the source code only so far).Changing the encoding of an array/iteratively (PDO comment)
As you wrote in a comment that you have problems to apply the function onto an array, here is some code example. It's always needed to first change the encoding before using
json_encode
. That's just a standard array operation, for the simpler case ofpdo::fetch()
aforeach
iteration: