我实际上是第一次在日本工作,我遇到了编码问题。 我正在编写一个小的PHP测试脚本来解析JSON中一些来自SQL数据库的数据。
SQL数据库以UTF-8编码,表中包含英语和日语的项目。
测试脚本:
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();
当我使用日语参数执行时,我收到编码错误:
[{"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":"?????"}]
我尝试了许多不成功的事情......有什么想法吗?
PS:我知道我的剧本既不好又安全,只是一个考验。由于
答案 0 :(得分:0)
引用@Matt Lowden回答 - Here
我倾向于找到解决问题的东西;
mysql_query("SET NAMES 'utf8'");
在执行任何查询之前。
文档建议您使用mysql_set_charset,但我经常看到该函数丢失。
if( function_exists('mysql_set_charset') ){
mysql_set_charset('utf8', $db_con);
}else{
mysql_query("SET NAMES 'utf8'", $db_con);
}