1

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?

nwellnhof
  • 32,319
  • 7
  • 89
  • 113
yarek
  • 11,278
  • 30
  • 120
  • 219
  • http://stackoverflow.com/questions/6606713/json-encode-non-utf-8-strings, does this help? – codisfy Feb 20 '16 at 15:56
  • just to clear up a point: JSON requires/is-specified only for unicode standard (where utf-8 is a specific encoding that fits). So the statement `use json_encode without UTF8` makes no real sense. – birdspider Feb 22 '16 at 16:19

2 Answers2

1

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"}
nwellnhof
  • 32,319
  • 7
  • 89
  • 113
1

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.

deceze
  • 510,633
  • 85
  • 743
  • 889