Question marks instead of Japanese characters in P

2019-09-16 01:20发布

I'm actually working in Japan for the first time and I got stuck in an encoding problem. I'm writing a small PHP test script to parse in JSON some data from a SQL Database.

The SQL database is encode in UTF-8 and the table have item in both English and Japanese.

The test script:

header('content-type: text/html; charset=UTF-8');
$link = mysql_connect(DB_NAME, USER_NAME, USER_PASS);
mysql_select_db(SCHEMA_NAME);
$sql = mysql_query("SELECT tab.id, tab.name, tab.indexDescription, gh_region.name AS region\n"
. "FROM (SELECT * FROM gh_building WHERE langId = " . $_GET["lang"] . " AND isPublished = 1) AS tab\n"
. "INNER JOIN gh_region\n"
. "ON tab.regionId = gh_region.id AND tab.langId = gh_region.langId");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print( json_encode($output) );
mysql_close();

When I'm executing it with the Japanese parameters, I'm getting an encoding error:

[{"id":"1","name":"?????","indexDescription":"??????????????????????JR?????????10?? ","region":"??"},{"id":"3","name":"??????","indexDescription":"??????????????????????????????????????? ??????????????????????? ","region":"??"},{"id":"4","name":"??????","indexDescription":"????????????????????????????????","region":"??"},{"id":"5","name":"?????","indexDescription":"???????????????!?????????????????????????? ","region":"??"},{"id":"6","name":"????","indexDescription":"???????????????????????? ?95????????","region":"??"},{"id":"7","name":"???????","indexDescription":"????????????????? ????????????","region":"??"},{"id":"8","name":"GH??","indexDescription":"????????????????????????????????????????????????????????????","region":"??"},{"id":"2","name":"?????(????) ","indexDescription":"????????????(??????)? ????????????\r\n??????????????","region":"??"},{"id":"9","name":"?????2","indexDescription":"???????????????? ????????????\r\n??????????","region":"??"},{"id":"10","name":"???????????","indexDescription":"","region":"?????"},{"id":"12","name":"??????","indexDescription":"","region":"?????"}]

I have try many things unsuccessfully ... Any idea ?

PS : I know my script isn't good and safe, it's just a test.

Thanks

1条回答
家丑人穷心不美
2楼-- · 2019-09-16 01:45

Quoted @Matt Lowden answer - Here

What I tend to find solves things a lot is;

mysql_query("SET NAMES 'utf8'");

Before any queries are performed.

The documentation recommends that you use mysql_set_charset but I often see that function missing.

if( function_exists('mysql_set_charset') ){
    mysql_set_charset('utf8', $db_con);
}else{
    mysql_query("SET NAMES 'utf8'", $db_con);
}
查看更多
登录 后发表回答