开发者

php utf8_encode - chars get prepended with \u

开发者 https://www.devze.com 2023-04-11 15:17 出处:网络
I\'ve got an ISO string that I fetch from database, and when I utf8_e开发者_如何转开发ncode it, I get a \\u00f6 instead of Ö. This confuses the javascript/html which ajaxes this PHP script. Why is th

I've got an ISO string that I fetch from database, and when I utf8_e开发者_如何转开发ncode it, I get a \u00f6 instead of Ö. This confuses the javascript/html which ajaxes this PHP script. Why is there a \u00f6 instead of Ö? How to get Ö instead?

edit: Ok, I did some more experimenting and it turns out this is caused by combination of utf8_encode and json_encode. Though if I don't utf8_encode at all, the value will be null in the json.

json_encode(array("city"=>utf8_encode("göteborg")))


utf8_encode doesn't encode characters to \uxxxx, as you figured out yourself it's json_encode doing this. And that's fine, because the JSON format specifies this behavior. If your client properly decodes the JSON string into a Javascript data type, the \uxxxx escapes will be turned into proper Unicode characters.

As for json_encode discarding characters if your string is Latin1 encoded: It's not explicitly stated on the manual page, but Javascript and JSON are entirely Unicode based, so I suspect Latin1 is an invalid and unexpected encoding to use with JSON strings, so it breaks.


How do you print that? javascript natively support \uXXXX encoding, and doing this in javascript:

var x = "\u00f6"; alert(x); 

should print out a small ö.

EDIT: According to your code, if you output that directly to the response stream and use the actual response as a variable in js on the client side, you shouldn't care about json_encode at all.

You would just tell the browser that the content is utf8 by setting the content-type header:

header('content-type: text/plain;charset=utf8');

And then the jQuery.data() code would work just fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号