带有utf-8字符的php-json输出Web服务问题(希腊语) [英] php-json output web service problem with utf-8 characters (greek)
问题描述
我是PHP&的新手. JSON,并基于一个教程,我制作了一个简单的Web服务,该服务返回mysql db表的内容.
I am new to PHP & JSON and based on a tutorial I made a simple web service which returns the contents of a table of a mysql db.
输出采用XML和JSON格式,并且数据库特征集为UTF-8.我的问题是某些字段包含希腊字符,并且不能以JSON输出格式正确显示(在XML中一切正常).知道有什么问题吗?
The output is in both XML and JSON and the database caracter set is UTF-8. my problem is that some fields contain Greek characters and do not appear correctly in the JSON output format (in XML everything is fine). Any idea what might be wrong?
PHP文件如下:
<?php
/* require the place_name_en as the parameter */
/* soak in the passed variable or set our own */
$number_of_places = isset($_GET['num']) ? intval($_GET['num']) : 1; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
/* connect to the db */
$link = mysql_connect('xxx','xxx','xxx') or die('Cannot connect to the DB');
mysql_select_db('foodbar',$link) or die('Cannot select the DB');
mysql_set_charset('utf8',$link);
mysql_query('set names utf8');
/* grab the posts from the db */
$query = 'SELECT * FROM test';
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($place = mysql_fetch_assoc($result)) {
$places[] = array('place'=>$place);
}
}
if($format == 'json') {
/* output in json format */
header('Content-type: application/json');
echo json_encode(array('places'=>$places));
}
else {
/* output in xml format */
header('Content-type: text/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<places>';
foreach($places as $index => $place) {
if(is_array($place)) {
foreach($place as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
/*echo '<',$tag,'>',htmlentities($val,ENT_QUOTES,"utf-8"),'</',$tag,'>';*/
echo '<',$tag,'>',$val,'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '</places>';
}
@mysql_close($link);
?>
您可以在此处进行测试.
但是,当返回 json格式时,希腊字符存在问题.它们显示为:
But when json format is returned there is a problem with Greek characters. they appear like:
\ u03b4 \ u03b4 \ u03b5 \ u03c3 \ u03c3 \ u03b4 \ u03b4 \ u03c6
\u03b4\u03b4\u03b5\u03c3\u03c3\u03b4\u03b4\u03c6
有什么主意吗?预先谢谢你!
Any idea? Thank you in advance!
P.S.数据库设置:MySQL字符集:UTF-8 Unicode(utf8)和MySQL连接排序规则:utf_8_unicode_ci
P.S. DB settings: MySQL charset: UTF-8 Unicode (utf8) and MySQL connection collation: utf_8_unicode_ci
推荐答案
json_encode()
将unicode字符编码为\uxxxx
序列.这是正常的. JS会理解他们的
json_encode()
encodes unicode characters to \uxxxx
sequences. It's normal. JS will understand them
这篇关于带有utf-8字符的php-json输出Web服务问题(希腊语)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!