我是PHP新手& JSON和基於教程我做了一個簡單的web服務,它返回mysql db表的內容。php-json utf-8字符輸出web服務問題(希臘語)
輸出既包含XML也包含JSON,並且數據庫字符集爲UTF-8。我的問題是某些字段包含希臘字符,並且不能以JSON輸出格式正確顯示(在XML中一切正常)。任何想法可能是錯誤的?
的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);
?>
您可以測試XML輸出here。
但是,當返回json format時,希臘字符出現問題。它們看起來像:
\ u03b4 \ u03b4 \ u03b5 \ u03c3 \ u03c3 \ u03b4 \ u03b4 \ u03c6
任何想法?先謝謝你!
P.S.數據庫設置:MySQL字符集:UTF-8 Unicode(utf8)和MySQL連接歸類:utf_8_unicode_ci
你爲什麼認爲json輸出不正確?這些'\ u ...'實際上是正確的javascript。 – hakre
我發現在php 5.4.0中添加了json_encode JSON_UNESCAPED_UNICODE選項。 http://php.net/manual/en/function.json-encode.php – jcubic