I am working on an old existing website. All pages were encoded in ISO-European, including the MySQL database.
I want to add some AJAX using PHP's json_encode, which only supports UTF8.
Is there a solution to use json_encode without UTF8?
I am working on an old existing website. All pages were encoded in ISO-European, including the MySQL database.
I want to add some AJAX using PHP's json_encode, which only supports UTF8.
Is there a solution to use json_encode without UTF8?
You can use var_export
, utf8_encode
and eval
to convert an array to UTF-8 recursively. It's a bit of a hack, but something like the following works:
$obj = array("key" => "\xC4rger"); // "Ärger" in Latin1
eval('$utf8_obj = ' . utf8_encode(var_export($obj, TRUE)) . ';');
print json_encode($utf8_obj);
This will print
{"key":"\u00c4rger"}
The only thing you need to do is to convert your data to UTF-8 before passing it to json_encode
. That function requires UTF-8 data, and unless you want to reimplement json_encode
yourself it's a lot easier to go along with its requirements:
function recursivelyConvertToUTF8($data, $from = 'ISO-8859-1') {
if (!is_array($data)) {
return iconv($from, 'UTF-8', $data);
}
return array_map(function ($value) use ($from) {
return recursivelyConvertToUTF8($value, $from);
}, $data);
}
echo json_encode(recursivelyConvertToUTF8($myData));
This is not necessarily a complete solution covering every possible use case, but it should illustrate the idea.