json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT

我是研究僧i 提交于 2019-11-26 18:34:18

问题


I have an annoying problem with a database query to mssql. If the result contains special characters like the german 'ä', I cannot use json_encode to get the result as json correctly.

json_last_error return 5 which is equal to JSON_ERROR_UTF8. I guess the database does not return the values as UTF-8 encoded. The database collection is *Latin1_General_CI_AS* and the affected columns are varchars.

The php mssql.charset configuration has no effect.

I read that mysql users could use mysql_query('SET CHARACTER SET utf8'); to encode the return values correctly. What can I do, to get the values correctly for mssql?

Hint - I cannot change the anything at the database.


回答1:


Before you JSON encode, use utf8_encode() around the string.




回答2:


You can just set this in your connection also:

$result = sqlsrv_connect($hostname, array(
    'UID' => $username,
    'PWD' => $password,
    'Database' => $database,
    "CharacterSet" => "UTF-8"   // <---- here the magic happens 
));

For me, this is the easer way.



来源:https://stackoverflow.com/questions/18247737/json-encode-produce-json-error-utf8-from-mssql-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!