php-json输出具有utf-8字符的web服务问题(希腊语)


php-json output web service problem with utf-8 characters (greek)

我是PHP&JSON,基于一个教程,我制作了一个简单的web服务,它返回mysqldb的表的内容。

输出为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输出。

但是当返回json格式时,希腊字符会出现问题。它们看起来像:

''u03b4''u03b4''u03b5''u03c3''u03c3''u03b4/u03b4 ''u03c6

知道吗?提前谢谢!

p.S.数据库设置:MySQL字符集:UTF-8 Unicode(utf8)和MySQL连接排序规则:UTF_8_Unicode_ci

json_encode()将unicode字符编码为'uxxxx序列。这很正常。JS将理解它们