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?

2
  • stackoverflow.com/questions/6606713/…, does this help? Commented Feb 20, 2016 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. Commented Feb 22, 2016 at 16:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"}

1 Comment

There's gotta be a saner way to do that besides eval...!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.